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 environment.clone(),
898 toolchain_store.read(cx).as_language_toolchain_store(),
899 worktree_store.clone(),
900 breakpoint_store.clone(),
901 cx,
902 )
903 });
904 cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
905
906 let image_store = cx.new(|cx| ImageStore::local(worktree_store.clone(), cx));
907 cx.subscribe(&image_store, Self::on_image_store_event)
908 .detach();
909
910 let prettier_store = cx.new(|cx| {
911 PrettierStore::new(
912 node.clone(),
913 fs.clone(),
914 languages.clone(),
915 worktree_store.clone(),
916 cx,
917 )
918 });
919
920 let task_store = cx.new(|cx| {
921 TaskStore::local(
922 buffer_store.downgrade(),
923 worktree_store.clone(),
924 toolchain_store.read(cx).as_language_toolchain_store(),
925 environment.clone(),
926 cx,
927 )
928 });
929
930 let settings_observer = cx.new(|cx| {
931 SettingsObserver::new_local(
932 fs.clone(),
933 worktree_store.clone(),
934 task_store.clone(),
935 cx,
936 )
937 });
938 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
939 .detach();
940
941 let lsp_store = cx.new(|cx| {
942 LspStore::new_local(
943 buffer_store.clone(),
944 worktree_store.clone(),
945 prettier_store.clone(),
946 toolchain_store.clone(),
947 environment.clone(),
948 languages.clone(),
949 client.http_client(),
950 fs.clone(),
951 cx,
952 )
953 });
954
955 let git_store = cx.new(|cx| {
956 GitStore::local(
957 &worktree_store,
958 buffer_store.clone(),
959 environment.clone(),
960 fs.clone(),
961 cx,
962 )
963 });
964
965 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
966
967 Self {
968 buffer_ordered_messages_tx: tx,
969 collaborators: Default::default(),
970 worktree_store,
971 buffer_store,
972 image_store,
973 lsp_store,
974 context_server_store,
975 join_project_response_message_id: 0,
976 client_state: ProjectClientState::Local,
977 git_store,
978 client_subscriptions: Vec::new(),
979 _subscriptions: vec![cx.on_release(Self::release)],
980 active_entry: None,
981 snippets,
982 languages,
983 client,
984 task_store,
985 user_store,
986 settings_observer,
987 fs,
988 ssh_client: None,
989 breakpoint_store,
990 dap_store,
991
992 buffers_needing_diff: Default::default(),
993 git_diff_debouncer: DebouncedDelay::new(),
994 terminals: Terminals {
995 local_handles: Vec::new(),
996 },
997 node: Some(node),
998 search_history: Self::new_search_history(),
999 environment,
1000 remotely_created_models: Default::default(),
1001
1002 search_included_history: Self::new_search_history(),
1003 search_excluded_history: Self::new_search_history(),
1004
1005 toolchain_store: Some(toolchain_store),
1006
1007 agent_location: None,
1008 }
1009 })
1010 }
1011
1012 pub fn ssh(
1013 ssh: Entity<SshRemoteClient>,
1014 client: Arc<Client>,
1015 node: NodeRuntime,
1016 user_store: Entity<UserStore>,
1017 languages: Arc<LanguageRegistry>,
1018 fs: Arc<dyn Fs>,
1019 cx: &mut App,
1020 ) -> Entity<Self> {
1021 cx.new(|cx: &mut Context<Self>| {
1022 let (tx, rx) = mpsc::unbounded();
1023 cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1024 .detach();
1025 let global_snippets_dir = paths::config_dir().join("snippets");
1026 let snippets =
1027 SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
1028
1029 let ssh_proto = ssh.read(cx).proto_client();
1030 let worktree_store =
1031 cx.new(|_| WorktreeStore::remote(false, ssh_proto.clone(), SSH_PROJECT_ID));
1032 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1033 .detach();
1034
1035 let context_server_store =
1036 cx.new(|cx| ContextServerStore::new(worktree_store.clone(), cx));
1037
1038 let buffer_store = cx.new(|cx| {
1039 BufferStore::remote(
1040 worktree_store.clone(),
1041 ssh.read(cx).proto_client(),
1042 SSH_PROJECT_ID,
1043 cx,
1044 )
1045 });
1046 let image_store = cx.new(|cx| {
1047 ImageStore::remote(
1048 worktree_store.clone(),
1049 ssh.read(cx).proto_client(),
1050 SSH_PROJECT_ID,
1051 cx,
1052 )
1053 });
1054 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1055 .detach();
1056 let toolchain_store = cx
1057 .new(|cx| ToolchainStore::remote(SSH_PROJECT_ID, ssh.read(cx).proto_client(), cx));
1058 let task_store = cx.new(|cx| {
1059 TaskStore::remote(
1060 buffer_store.downgrade(),
1061 worktree_store.clone(),
1062 toolchain_store.read(cx).as_language_toolchain_store(),
1063 ssh.read(cx).proto_client(),
1064 SSH_PROJECT_ID,
1065 cx,
1066 )
1067 });
1068
1069 let settings_observer = cx.new(|cx| {
1070 SettingsObserver::new_remote(
1071 fs.clone(),
1072 worktree_store.clone(),
1073 task_store.clone(),
1074 cx,
1075 )
1076 });
1077 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1078 .detach();
1079
1080 let environment = cx.new(|_| ProjectEnvironment::new(None));
1081
1082 let lsp_store = cx.new(|cx| {
1083 LspStore::new_remote(
1084 buffer_store.clone(),
1085 worktree_store.clone(),
1086 Some(toolchain_store.clone()),
1087 languages.clone(),
1088 ssh_proto.clone(),
1089 SSH_PROJECT_ID,
1090 fs.clone(),
1091 cx,
1092 )
1093 });
1094 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1095
1096 let breakpoint_store =
1097 cx.new(|_| BreakpointStore::remote(SSH_PROJECT_ID, ssh_proto.clone()));
1098
1099 let dap_store = cx.new(|cx| {
1100 DapStore::new_ssh(
1101 SSH_PROJECT_ID,
1102 ssh.clone(),
1103 breakpoint_store.clone(),
1104 worktree_store.clone(),
1105 cx,
1106 )
1107 });
1108
1109 let git_store = cx.new(|cx| {
1110 GitStore::ssh(&worktree_store, buffer_store.clone(), ssh_proto.clone(), cx)
1111 });
1112
1113 cx.subscribe(&ssh, Self::on_ssh_event).detach();
1114
1115 let this = Self {
1116 buffer_ordered_messages_tx: tx,
1117 collaborators: Default::default(),
1118 worktree_store,
1119 buffer_store,
1120 image_store,
1121 lsp_store,
1122 context_server_store,
1123 breakpoint_store,
1124 dap_store,
1125 join_project_response_message_id: 0,
1126 client_state: ProjectClientState::Local,
1127 git_store,
1128 client_subscriptions: Vec::new(),
1129 _subscriptions: vec![
1130 cx.on_release(Self::release),
1131 cx.on_app_quit(|this, cx| {
1132 let shutdown = this.ssh_client.take().and_then(|client| {
1133 client.read(cx).shutdown_processes(
1134 Some(proto::ShutdownRemoteServer {}),
1135 cx.background_executor().clone(),
1136 )
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.read(cx).shutdown_processes(
1477 Some(proto::ShutdownRemoteServer {}),
1478 cx.background_executor().clone(),
1479 );
1480
1481 cx.background_spawn(async move {
1482 if let Some(shutdown) = shutdown {
1483 shutdown.await;
1484 }
1485 })
1486 .detach()
1487 }
1488
1489 match &self.client_state {
1490 ProjectClientState::Local => {}
1491 ProjectClientState::Shared { .. } => {
1492 let _ = self.unshare_internal(cx);
1493 }
1494 ProjectClientState::Remote { remote_id, .. } => {
1495 let _ = self.client.send(proto::LeaveProject {
1496 project_id: *remote_id,
1497 });
1498 self.disconnected_from_host_internal(cx);
1499 }
1500 }
1501 }
1502
1503 #[cfg(any(test, feature = "test-support"))]
1504 pub async fn example(
1505 root_paths: impl IntoIterator<Item = &Path>,
1506 cx: &mut AsyncApp,
1507 ) -> Entity<Project> {
1508 use clock::FakeSystemClock;
1509
1510 let fs = Arc::new(RealFs::new(None, cx.background_executor().clone()));
1511 let languages = LanguageRegistry::test(cx.background_executor().clone());
1512 let clock = Arc::new(FakeSystemClock::new());
1513 let http_client = http_client::FakeHttpClient::with_404_response();
1514 let client = cx
1515 .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1516 .unwrap();
1517 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx)).unwrap();
1518 let project = cx
1519 .update(|cx| {
1520 Project::local(
1521 client,
1522 node_runtime::NodeRuntime::unavailable(),
1523 user_store,
1524 Arc::new(languages),
1525 fs,
1526 None,
1527 cx,
1528 )
1529 })
1530 .unwrap();
1531 for path in root_paths {
1532 let (tree, _) = project
1533 .update(cx, |project, cx| {
1534 project.find_or_create_worktree(path, true, cx)
1535 })
1536 .unwrap()
1537 .await
1538 .unwrap();
1539 tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1540 .unwrap()
1541 .await;
1542 }
1543 project
1544 }
1545
1546 #[cfg(any(test, feature = "test-support"))]
1547 pub async fn test(
1548 fs: Arc<dyn Fs>,
1549 root_paths: impl IntoIterator<Item = &Path>,
1550 cx: &mut gpui::TestAppContext,
1551 ) -> Entity<Project> {
1552 use clock::FakeSystemClock;
1553
1554 let languages = LanguageRegistry::test(cx.executor());
1555 let clock = Arc::new(FakeSystemClock::new());
1556 let http_client = http_client::FakeHttpClient::with_404_response();
1557 let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1558 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1559 let project = cx.update(|cx| {
1560 Project::local(
1561 client,
1562 node_runtime::NodeRuntime::unavailable(),
1563 user_store,
1564 Arc::new(languages),
1565 fs,
1566 None,
1567 cx,
1568 )
1569 });
1570 for path in root_paths {
1571 let (tree, _) = project
1572 .update(cx, |project, cx| {
1573 project.find_or_create_worktree(path, true, cx)
1574 })
1575 .await
1576 .unwrap();
1577
1578 tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1579 .await;
1580 }
1581 project
1582 }
1583
1584 pub fn dap_store(&self) -> Entity<DapStore> {
1585 self.dap_store.clone()
1586 }
1587
1588 pub fn breakpoint_store(&self) -> Entity<BreakpointStore> {
1589 self.breakpoint_store.clone()
1590 }
1591
1592 pub fn active_debug_session(&self, cx: &App) -> Option<(Entity<Session>, ActiveStackFrame)> {
1593 let active_position = self.breakpoint_store.read(cx).active_position()?;
1594 let session = self
1595 .dap_store
1596 .read(cx)
1597 .session_by_id(active_position.session_id)?;
1598 Some((session, active_position.clone()))
1599 }
1600
1601 pub fn lsp_store(&self) -> Entity<LspStore> {
1602 self.lsp_store.clone()
1603 }
1604
1605 pub fn worktree_store(&self) -> Entity<WorktreeStore> {
1606 self.worktree_store.clone()
1607 }
1608
1609 pub fn context_server_store(&self) -> Entity<ContextServerStore> {
1610 self.context_server_store.clone()
1611 }
1612
1613 pub fn buffer_for_id(&self, remote_id: BufferId, cx: &App) -> Option<Entity<Buffer>> {
1614 self.buffer_store.read(cx).get(remote_id)
1615 }
1616
1617 pub fn languages(&self) -> &Arc<LanguageRegistry> {
1618 &self.languages
1619 }
1620
1621 pub fn client(&self) -> Arc<Client> {
1622 self.client.clone()
1623 }
1624
1625 pub fn ssh_client(&self) -> Option<Entity<SshRemoteClient>> {
1626 self.ssh_client.clone()
1627 }
1628
1629 pub fn user_store(&self) -> Entity<UserStore> {
1630 self.user_store.clone()
1631 }
1632
1633 pub fn node_runtime(&self) -> Option<&NodeRuntime> {
1634 self.node.as_ref()
1635 }
1636
1637 pub fn opened_buffers(&self, cx: &App) -> Vec<Entity<Buffer>> {
1638 self.buffer_store.read(cx).buffers().collect()
1639 }
1640
1641 pub fn environment(&self) -> &Entity<ProjectEnvironment> {
1642 &self.environment
1643 }
1644
1645 pub fn cli_environment(&self, cx: &App) -> Option<HashMap<String, String>> {
1646 self.environment.read(cx).get_cli_environment()
1647 }
1648
1649 pub fn buffer_environment<'a>(
1650 &'a self,
1651 buffer: &Entity<Buffer>,
1652 worktree_store: &Entity<WorktreeStore>,
1653 cx: &'a mut App,
1654 ) -> Shared<Task<Option<HashMap<String, String>>>> {
1655 self.environment.update(cx, |environment, cx| {
1656 environment.get_buffer_environment(&buffer, &worktree_store, cx)
1657 })
1658 }
1659
1660 pub fn directory_environment(
1661 &self,
1662 abs_path: Arc<Path>,
1663 cx: &mut App,
1664 ) -> Shared<Task<Option<HashMap<String, String>>>> {
1665 self.environment.update(cx, |environment, cx| {
1666 environment.get_directory_environment(abs_path, cx)
1667 })
1668 }
1669
1670 pub fn shell_environment_errors<'a>(
1671 &'a self,
1672 cx: &'a App,
1673 ) -> impl Iterator<Item = (&'a Arc<Path>, &'a EnvironmentErrorMessage)> {
1674 self.environment.read(cx).environment_errors()
1675 }
1676
1677 pub fn remove_environment_error(&mut self, abs_path: &Path, cx: &mut Context<Self>) {
1678 self.environment.update(cx, |environment, cx| {
1679 environment.remove_environment_error(abs_path, cx);
1680 });
1681 }
1682
1683 #[cfg(any(test, feature = "test-support"))]
1684 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
1685 self.buffer_store
1686 .read(cx)
1687 .get_by_path(&path.into(), cx)
1688 .is_some()
1689 }
1690
1691 pub fn fs(&self) -> &Arc<dyn Fs> {
1692 &self.fs
1693 }
1694
1695 pub fn remote_id(&self) -> Option<u64> {
1696 match self.client_state {
1697 ProjectClientState::Local => None,
1698 ProjectClientState::Shared { remote_id, .. }
1699 | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1700 }
1701 }
1702
1703 pub fn supports_terminal(&self, _cx: &App) -> bool {
1704 if self.is_local() {
1705 return true;
1706 }
1707 if self.is_via_ssh() {
1708 return true;
1709 }
1710
1711 return false;
1712 }
1713
1714 pub fn ssh_connection_string(&self, cx: &App) -> Option<SharedString> {
1715 if let Some(ssh_state) = &self.ssh_client {
1716 return Some(ssh_state.read(cx).connection_string().into());
1717 }
1718
1719 return None;
1720 }
1721
1722 pub fn ssh_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
1723 self.ssh_client
1724 .as_ref()
1725 .map(|ssh| ssh.read(cx).connection_state())
1726 }
1727
1728 pub fn ssh_connection_options(&self, cx: &App) -> Option<SshConnectionOptions> {
1729 self.ssh_client
1730 .as_ref()
1731 .map(|ssh| ssh.read(cx).connection_options())
1732 }
1733
1734 pub fn replica_id(&self) -> ReplicaId {
1735 match self.client_state {
1736 ProjectClientState::Remote { replica_id, .. } => replica_id,
1737 _ => {
1738 if self.ssh_client.is_some() {
1739 1
1740 } else {
1741 0
1742 }
1743 }
1744 }
1745 }
1746
1747 pub fn task_store(&self) -> &Entity<TaskStore> {
1748 &self.task_store
1749 }
1750
1751 pub fn snippets(&self) -> &Entity<SnippetProvider> {
1752 &self.snippets
1753 }
1754
1755 pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1756 match kind {
1757 SearchInputKind::Query => &self.search_history,
1758 SearchInputKind::Include => &self.search_included_history,
1759 SearchInputKind::Exclude => &self.search_excluded_history,
1760 }
1761 }
1762
1763 pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1764 match kind {
1765 SearchInputKind::Query => &mut self.search_history,
1766 SearchInputKind::Include => &mut self.search_included_history,
1767 SearchInputKind::Exclude => &mut self.search_excluded_history,
1768 }
1769 }
1770
1771 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1772 &self.collaborators
1773 }
1774
1775 pub fn host(&self) -> Option<&Collaborator> {
1776 self.collaborators.values().find(|c| c.is_host)
1777 }
1778
1779 pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
1780 self.worktree_store.update(cx, |store, _| {
1781 store.set_worktrees_reordered(worktrees_reordered);
1782 });
1783 }
1784
1785 /// Collect all worktrees, including ones that don't appear in the project panel
1786 pub fn worktrees<'a>(
1787 &self,
1788 cx: &'a App,
1789 ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1790 self.worktree_store.read(cx).worktrees()
1791 }
1792
1793 /// Collect all user-visible worktrees, the ones that appear in the project panel.
1794 pub fn visible_worktrees<'a>(
1795 &'a self,
1796 cx: &'a App,
1797 ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1798 self.worktree_store.read(cx).visible_worktrees(cx)
1799 }
1800
1801 pub fn worktree_for_root_name(&self, root_name: &str, cx: &App) -> Option<Entity<Worktree>> {
1802 self.visible_worktrees(cx)
1803 .find(|tree| tree.read(cx).root_name() == root_name)
1804 }
1805
1806 pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
1807 self.visible_worktrees(cx)
1808 .map(|tree| tree.read(cx).root_name())
1809 }
1810
1811 pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
1812 self.worktree_store.read(cx).worktree_for_id(id, cx)
1813 }
1814
1815 pub fn worktree_for_entry(
1816 &self,
1817 entry_id: ProjectEntryId,
1818 cx: &App,
1819 ) -> Option<Entity<Worktree>> {
1820 self.worktree_store
1821 .read(cx)
1822 .worktree_for_entry(entry_id, cx)
1823 }
1824
1825 pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
1826 self.worktree_for_entry(entry_id, cx)
1827 .map(|worktree| worktree.read(cx).id())
1828 }
1829
1830 /// Checks if the entry is the root of a worktree.
1831 pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
1832 self.worktree_for_entry(entry_id, cx)
1833 .map(|worktree| {
1834 worktree
1835 .read(cx)
1836 .root_entry()
1837 .is_some_and(|e| e.id == entry_id)
1838 })
1839 .unwrap_or(false)
1840 }
1841
1842 pub fn project_path_git_status(
1843 &self,
1844 project_path: &ProjectPath,
1845 cx: &App,
1846 ) -> Option<FileStatus> {
1847 self.git_store
1848 .read(cx)
1849 .project_path_git_status(project_path, cx)
1850 }
1851
1852 pub fn visibility_for_paths(
1853 &self,
1854 paths: &[PathBuf],
1855 metadatas: &[Metadata],
1856 exclude_sub_dirs: bool,
1857 cx: &App,
1858 ) -> Option<bool> {
1859 paths
1860 .iter()
1861 .zip(metadatas)
1862 .map(|(path, metadata)| self.visibility_for_path(path, metadata, exclude_sub_dirs, cx))
1863 .max()
1864 .flatten()
1865 }
1866
1867 pub fn visibility_for_path(
1868 &self,
1869 path: &Path,
1870 metadata: &Metadata,
1871 exclude_sub_dirs: bool,
1872 cx: &App,
1873 ) -> Option<bool> {
1874 let sanitized_path = SanitizedPath::from(path);
1875 let path = sanitized_path.as_path();
1876 self.worktrees(cx)
1877 .filter_map(|worktree| {
1878 let worktree = worktree.read(cx);
1879 let abs_path = worktree.as_local()?.abs_path();
1880 let contains = path == abs_path
1881 || (path.starts_with(abs_path) && (!exclude_sub_dirs || !metadata.is_dir));
1882 contains.then(|| worktree.is_visible())
1883 })
1884 .max()
1885 }
1886
1887 pub fn create_entry(
1888 &mut self,
1889 project_path: impl Into<ProjectPath>,
1890 is_directory: bool,
1891 cx: &mut Context<Self>,
1892 ) -> Task<Result<CreatedEntry>> {
1893 let project_path = project_path.into();
1894 let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1895 return Task::ready(Err(anyhow!(format!(
1896 "No worktree for path {project_path:?}"
1897 ))));
1898 };
1899 worktree.update(cx, |worktree, cx| {
1900 worktree.create_entry(project_path.path, is_directory, None, cx)
1901 })
1902 }
1903
1904 pub fn copy_entry(
1905 &mut self,
1906 entry_id: ProjectEntryId,
1907 relative_worktree_source_path: Option<PathBuf>,
1908 new_path: impl Into<Arc<Path>>,
1909 cx: &mut Context<Self>,
1910 ) -> Task<Result<Option<Entry>>> {
1911 let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1912 return Task::ready(Ok(None));
1913 };
1914 worktree.update(cx, |worktree, cx| {
1915 worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1916 })
1917 }
1918
1919 /// Renames the project entry with given `entry_id`.
1920 ///
1921 /// `new_path` is a relative path to worktree root.
1922 /// If root entry is renamed then its new root name is used instead.
1923 pub fn rename_entry(
1924 &mut self,
1925 entry_id: ProjectEntryId,
1926 new_path: impl Into<Arc<Path>>,
1927 cx: &mut Context<Self>,
1928 ) -> Task<Result<CreatedEntry>> {
1929 let worktree_store = self.worktree_store.read(cx);
1930 let new_path = new_path.into();
1931 let Some((worktree, old_path, is_dir)) = worktree_store
1932 .worktree_and_entry_for_id(entry_id, cx)
1933 .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
1934 else {
1935 return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1936 };
1937
1938 let worktree_id = worktree.read(cx).id();
1939 let is_root_entry = self.entry_is_worktree_root(entry_id, cx);
1940
1941 let lsp_store = self.lsp_store().downgrade();
1942 cx.spawn(async move |_, cx| {
1943 let (old_abs_path, new_abs_path) = {
1944 let root_path = worktree.update(cx, |this, _| this.abs_path())?;
1945 let new_abs_path = if is_root_entry {
1946 root_path.parent().unwrap().join(&new_path)
1947 } else {
1948 root_path.join(&new_path)
1949 };
1950 (root_path.join(&old_path), new_abs_path)
1951 };
1952 LspStore::will_rename_entry(
1953 lsp_store.clone(),
1954 worktree_id,
1955 &old_abs_path,
1956 &new_abs_path,
1957 is_dir,
1958 cx.clone(),
1959 )
1960 .await;
1961
1962 let entry = worktree
1963 .update(cx, |worktree, cx| {
1964 worktree.rename_entry(entry_id, new_path.clone(), cx)
1965 })?
1966 .await?;
1967
1968 lsp_store
1969 .update(cx, |this, _| {
1970 this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
1971 })
1972 .ok();
1973 Ok(entry)
1974 })
1975 }
1976
1977 pub fn delete_file(
1978 &mut self,
1979 path: ProjectPath,
1980 trash: bool,
1981 cx: &mut Context<Self>,
1982 ) -> Option<Task<Result<()>>> {
1983 let entry = self.entry_for_path(&path, cx)?;
1984 self.delete_entry(entry.id, trash, cx)
1985 }
1986
1987 pub fn delete_entry(
1988 &mut self,
1989 entry_id: ProjectEntryId,
1990 trash: bool,
1991 cx: &mut Context<Self>,
1992 ) -> Option<Task<Result<()>>> {
1993 let worktree = self.worktree_for_entry(entry_id, cx)?;
1994 cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
1995 worktree.update(cx, |worktree, cx| {
1996 worktree.delete_entry(entry_id, trash, cx)
1997 })
1998 }
1999
2000 pub fn expand_entry(
2001 &mut self,
2002 worktree_id: WorktreeId,
2003 entry_id: ProjectEntryId,
2004 cx: &mut Context<Self>,
2005 ) -> Option<Task<Result<()>>> {
2006 let worktree = self.worktree_for_id(worktree_id, cx)?;
2007 worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
2008 }
2009
2010 pub fn expand_all_for_entry(
2011 &mut self,
2012 worktree_id: WorktreeId,
2013 entry_id: ProjectEntryId,
2014 cx: &mut Context<Self>,
2015 ) -> Option<Task<Result<()>>> {
2016 let worktree = self.worktree_for_id(worktree_id, cx)?;
2017 let task = worktree.update(cx, |worktree, cx| {
2018 worktree.expand_all_for_entry(entry_id, cx)
2019 });
2020 Some(cx.spawn(async move |this, cx| {
2021 task.ok_or_else(|| anyhow!("no task"))?.await?;
2022 this.update(cx, |_, cx| {
2023 cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
2024 })?;
2025 Ok(())
2026 }))
2027 }
2028
2029 pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
2030 if !matches!(self.client_state, ProjectClientState::Local) {
2031 return Err(anyhow!("project was already shared"));
2032 }
2033
2034 self.client_subscriptions.extend([
2035 self.client
2036 .subscribe_to_entity(project_id)?
2037 .set_entity(&cx.entity(), &mut cx.to_async()),
2038 self.client
2039 .subscribe_to_entity(project_id)?
2040 .set_entity(&self.worktree_store, &mut cx.to_async()),
2041 self.client
2042 .subscribe_to_entity(project_id)?
2043 .set_entity(&self.buffer_store, &mut cx.to_async()),
2044 self.client
2045 .subscribe_to_entity(project_id)?
2046 .set_entity(&self.lsp_store, &mut cx.to_async()),
2047 self.client
2048 .subscribe_to_entity(project_id)?
2049 .set_entity(&self.settings_observer, &mut cx.to_async()),
2050 self.client
2051 .subscribe_to_entity(project_id)?
2052 .set_entity(&self.dap_store, &mut cx.to_async()),
2053 self.client
2054 .subscribe_to_entity(project_id)?
2055 .set_entity(&self.breakpoint_store, &mut cx.to_async()),
2056 self.client
2057 .subscribe_to_entity(project_id)?
2058 .set_entity(&self.git_store, &mut cx.to_async()),
2059 ]);
2060
2061 self.buffer_store.update(cx, |buffer_store, cx| {
2062 buffer_store.shared(project_id, self.client.clone().into(), cx)
2063 });
2064 self.worktree_store.update(cx, |worktree_store, cx| {
2065 worktree_store.shared(project_id, self.client.clone().into(), cx);
2066 });
2067 self.lsp_store.update(cx, |lsp_store, cx| {
2068 lsp_store.shared(project_id, self.client.clone().into(), cx)
2069 });
2070 self.breakpoint_store.update(cx, |breakpoint_store, _| {
2071 breakpoint_store.shared(project_id, self.client.clone().into())
2072 });
2073 self.dap_store.update(cx, |dap_store, cx| {
2074 dap_store.shared(project_id, self.client.clone().into(), cx);
2075 });
2076 self.task_store.update(cx, |task_store, cx| {
2077 task_store.shared(project_id, self.client.clone().into(), cx);
2078 });
2079 self.settings_observer.update(cx, |settings_observer, cx| {
2080 settings_observer.shared(project_id, self.client.clone().into(), cx)
2081 });
2082 self.git_store.update(cx, |git_store, cx| {
2083 git_store.shared(project_id, self.client.clone().into(), cx)
2084 });
2085
2086 self.client_state = ProjectClientState::Shared {
2087 remote_id: project_id,
2088 };
2089
2090 cx.emit(Event::RemoteIdChanged(Some(project_id)));
2091 Ok(())
2092 }
2093
2094 pub fn reshared(
2095 &mut self,
2096 message: proto::ResharedProject,
2097 cx: &mut Context<Self>,
2098 ) -> Result<()> {
2099 self.buffer_store
2100 .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
2101 self.set_collaborators_from_proto(message.collaborators, cx)?;
2102
2103 self.worktree_store.update(cx, |worktree_store, cx| {
2104 worktree_store.send_project_updates(cx);
2105 });
2106 if let Some(remote_id) = self.remote_id() {
2107 self.git_store.update(cx, |git_store, cx| {
2108 git_store.shared(remote_id, self.client.clone().into(), cx)
2109 });
2110 }
2111 cx.emit(Event::Reshared);
2112 Ok(())
2113 }
2114
2115 pub fn rejoined(
2116 &mut self,
2117 message: proto::RejoinedProject,
2118 message_id: u32,
2119 cx: &mut Context<Self>,
2120 ) -> Result<()> {
2121 cx.update_global::<SettingsStore, _>(|store, cx| {
2122 self.worktree_store.update(cx, |worktree_store, cx| {
2123 for worktree in worktree_store.worktrees() {
2124 store
2125 .clear_local_settings(worktree.read(cx).id(), cx)
2126 .log_err();
2127 }
2128 });
2129 });
2130
2131 self.join_project_response_message_id = message_id;
2132 self.set_worktrees_from_proto(message.worktrees, cx)?;
2133 self.set_collaborators_from_proto(message.collaborators, cx)?;
2134 self.lsp_store.update(cx, |lsp_store, _| {
2135 lsp_store.set_language_server_statuses_from_proto(message.language_servers)
2136 });
2137 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
2138 .unwrap();
2139 cx.emit(Event::Rejoined);
2140 Ok(())
2141 }
2142
2143 pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
2144 self.unshare_internal(cx)?;
2145 cx.emit(Event::RemoteIdChanged(None));
2146 Ok(())
2147 }
2148
2149 fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
2150 if self.is_via_collab() {
2151 return Err(anyhow!("attempted to unshare a remote project"));
2152 }
2153
2154 if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
2155 self.client_state = ProjectClientState::Local;
2156 self.collaborators.clear();
2157 self.client_subscriptions.clear();
2158 self.worktree_store.update(cx, |store, cx| {
2159 store.unshared(cx);
2160 });
2161 self.buffer_store.update(cx, |buffer_store, cx| {
2162 buffer_store.forget_shared_buffers();
2163 buffer_store.unshared(cx)
2164 });
2165 self.task_store.update(cx, |task_store, cx| {
2166 task_store.unshared(cx);
2167 });
2168 self.breakpoint_store.update(cx, |breakpoint_store, cx| {
2169 breakpoint_store.unshared(cx);
2170 });
2171 self.dap_store.update(cx, |dap_store, cx| {
2172 dap_store.unshared(cx);
2173 });
2174 self.settings_observer.update(cx, |settings_observer, cx| {
2175 settings_observer.unshared(cx);
2176 });
2177 self.git_store.update(cx, |git_store, cx| {
2178 git_store.unshared(cx);
2179 });
2180
2181 self.client
2182 .send(proto::UnshareProject {
2183 project_id: remote_id,
2184 })
2185 .ok();
2186 Ok(())
2187 } else {
2188 Err(anyhow!("attempted to unshare an unshared project"))
2189 }
2190 }
2191
2192 pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
2193 if self.is_disconnected(cx) {
2194 return;
2195 }
2196 self.disconnected_from_host_internal(cx);
2197 cx.emit(Event::DisconnectedFromHost);
2198 }
2199
2200 pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
2201 let new_capability =
2202 if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
2203 Capability::ReadWrite
2204 } else {
2205 Capability::ReadOnly
2206 };
2207 if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
2208 if *capability == new_capability {
2209 return;
2210 }
2211
2212 *capability = new_capability;
2213 for buffer in self.opened_buffers(cx) {
2214 buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
2215 }
2216 }
2217 }
2218
2219 fn disconnected_from_host_internal(&mut self, cx: &mut App) {
2220 if let ProjectClientState::Remote {
2221 sharing_has_stopped,
2222 ..
2223 } = &mut self.client_state
2224 {
2225 *sharing_has_stopped = true;
2226 self.collaborators.clear();
2227 self.worktree_store.update(cx, |store, cx| {
2228 store.disconnected_from_host(cx);
2229 });
2230 self.buffer_store.update(cx, |buffer_store, cx| {
2231 buffer_store.disconnected_from_host(cx)
2232 });
2233 self.lsp_store
2234 .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
2235 }
2236 }
2237
2238 pub fn close(&mut self, cx: &mut Context<Self>) {
2239 cx.emit(Event::Closed);
2240 }
2241
2242 pub fn is_disconnected(&self, cx: &App) -> bool {
2243 match &self.client_state {
2244 ProjectClientState::Remote {
2245 sharing_has_stopped,
2246 ..
2247 } => *sharing_has_stopped,
2248 ProjectClientState::Local if self.is_via_ssh() => self.ssh_is_disconnected(cx),
2249 _ => false,
2250 }
2251 }
2252
2253 fn ssh_is_disconnected(&self, cx: &App) -> bool {
2254 self.ssh_client
2255 .as_ref()
2256 .map(|ssh| ssh.read(cx).is_disconnected())
2257 .unwrap_or(false)
2258 }
2259
2260 pub fn capability(&self) -> Capability {
2261 match &self.client_state {
2262 ProjectClientState::Remote { capability, .. } => *capability,
2263 ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
2264 }
2265 }
2266
2267 pub fn is_read_only(&self, cx: &App) -> bool {
2268 self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
2269 }
2270
2271 pub fn is_local(&self) -> bool {
2272 match &self.client_state {
2273 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2274 self.ssh_client.is_none()
2275 }
2276 ProjectClientState::Remote { .. } => false,
2277 }
2278 }
2279
2280 pub fn is_via_ssh(&self) -> bool {
2281 match &self.client_state {
2282 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2283 self.ssh_client.is_some()
2284 }
2285 ProjectClientState::Remote { .. } => false,
2286 }
2287 }
2288
2289 pub fn is_via_collab(&self) -> bool {
2290 match &self.client_state {
2291 ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
2292 ProjectClientState::Remote { .. } => true,
2293 }
2294 }
2295
2296 pub fn create_buffer(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
2297 self.buffer_store
2298 .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx))
2299 }
2300
2301 pub fn create_local_buffer(
2302 &mut self,
2303 text: &str,
2304 language: Option<Arc<Language>>,
2305 cx: &mut Context<Self>,
2306 ) -> Entity<Buffer> {
2307 if self.is_via_collab() || self.is_via_ssh() {
2308 panic!("called create_local_buffer on a remote project")
2309 }
2310 self.buffer_store.update(cx, |buffer_store, cx| {
2311 buffer_store.create_local_buffer(text, language, cx)
2312 })
2313 }
2314
2315 pub fn open_path(
2316 &mut self,
2317 path: ProjectPath,
2318 cx: &mut Context<Self>,
2319 ) -> Task<Result<(Option<ProjectEntryId>, AnyEntity)>> {
2320 let task = self.open_buffer(path.clone(), cx);
2321 cx.spawn(async move |_project, cx| {
2322 let buffer = task.await?;
2323 let project_entry_id = buffer.read_with(cx, |buffer, cx| {
2324 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
2325 })?;
2326
2327 let buffer: &AnyEntity = &buffer;
2328 Ok((project_entry_id, buffer.clone()))
2329 })
2330 }
2331
2332 pub fn open_local_buffer(
2333 &mut self,
2334 abs_path: impl AsRef<Path>,
2335 cx: &mut Context<Self>,
2336 ) -> Task<Result<Entity<Buffer>>> {
2337 if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2338 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
2339 } else {
2340 Task::ready(Err(anyhow!("no such path")))
2341 }
2342 }
2343
2344 #[cfg(any(test, feature = "test-support"))]
2345 pub fn open_local_buffer_with_lsp(
2346 &mut self,
2347 abs_path: impl AsRef<Path>,
2348 cx: &mut Context<Self>,
2349 ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2350 if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2351 self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
2352 } else {
2353 Task::ready(Err(anyhow!("no such path")))
2354 }
2355 }
2356
2357 pub fn open_buffer(
2358 &mut self,
2359 path: impl Into<ProjectPath>,
2360 cx: &mut App,
2361 ) -> Task<Result<Entity<Buffer>>> {
2362 if self.is_disconnected(cx) {
2363 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2364 }
2365
2366 self.buffer_store.update(cx, |buffer_store, cx| {
2367 buffer_store.open_buffer(path.into(), cx)
2368 })
2369 }
2370
2371 #[cfg(any(test, feature = "test-support"))]
2372 pub fn open_buffer_with_lsp(
2373 &mut self,
2374 path: impl Into<ProjectPath>,
2375 cx: &mut Context<Self>,
2376 ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2377 let buffer = self.open_buffer(path, cx);
2378 cx.spawn(async move |this, cx| {
2379 let buffer = buffer.await?;
2380 let handle = this.update(cx, |project, cx| {
2381 project.register_buffer_with_language_servers(&buffer, cx)
2382 })?;
2383 Ok((buffer, handle))
2384 })
2385 }
2386
2387 pub fn register_buffer_with_language_servers(
2388 &self,
2389 buffer: &Entity<Buffer>,
2390 cx: &mut App,
2391 ) -> OpenLspBufferHandle {
2392 self.lsp_store.update(cx, |lsp_store, cx| {
2393 lsp_store.register_buffer_with_language_servers(&buffer, false, cx)
2394 })
2395 }
2396
2397 pub fn open_unstaged_diff(
2398 &mut self,
2399 buffer: Entity<Buffer>,
2400 cx: &mut Context<Self>,
2401 ) -> Task<Result<Entity<BufferDiff>>> {
2402 if self.is_disconnected(cx) {
2403 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2404 }
2405 self.git_store
2406 .update(cx, |git_store, cx| git_store.open_unstaged_diff(buffer, cx))
2407 }
2408
2409 pub fn open_uncommitted_diff(
2410 &mut self,
2411 buffer: Entity<Buffer>,
2412 cx: &mut Context<Self>,
2413 ) -> Task<Result<Entity<BufferDiff>>> {
2414 if self.is_disconnected(cx) {
2415 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2416 }
2417 self.git_store.update(cx, |git_store, cx| {
2418 git_store.open_uncommitted_diff(buffer, cx)
2419 })
2420 }
2421
2422 pub fn open_buffer_by_id(
2423 &mut self,
2424 id: BufferId,
2425 cx: &mut Context<Self>,
2426 ) -> Task<Result<Entity<Buffer>>> {
2427 if let Some(buffer) = self.buffer_for_id(id, cx) {
2428 Task::ready(Ok(buffer))
2429 } else if self.is_local() || self.is_via_ssh() {
2430 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
2431 } else if let Some(project_id) = self.remote_id() {
2432 let request = self.client.request(proto::OpenBufferById {
2433 project_id,
2434 id: id.into(),
2435 });
2436 cx.spawn(async move |project, cx| {
2437 let buffer_id = BufferId::new(request.await?.buffer_id)?;
2438 project
2439 .update(cx, |project, cx| {
2440 project.buffer_store.update(cx, |buffer_store, cx| {
2441 buffer_store.wait_for_remote_buffer(buffer_id, cx)
2442 })
2443 })?
2444 .await
2445 })
2446 } else {
2447 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
2448 }
2449 }
2450
2451 pub fn save_buffers(
2452 &self,
2453 buffers: HashSet<Entity<Buffer>>,
2454 cx: &mut Context<Self>,
2455 ) -> Task<Result<()>> {
2456 cx.spawn(async move |this, cx| {
2457 let save_tasks = buffers.into_iter().filter_map(|buffer| {
2458 this.update(cx, |this, cx| this.save_buffer(buffer, cx))
2459 .ok()
2460 });
2461 try_join_all(save_tasks).await?;
2462 Ok(())
2463 })
2464 }
2465
2466 pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
2467 self.buffer_store
2468 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
2469 }
2470
2471 pub fn save_buffer_as(
2472 &mut self,
2473 buffer: Entity<Buffer>,
2474 path: ProjectPath,
2475 cx: &mut Context<Self>,
2476 ) -> Task<Result<()>> {
2477 self.buffer_store.update(cx, |buffer_store, cx| {
2478 buffer_store.save_buffer_as(buffer.clone(), path, cx)
2479 })
2480 }
2481
2482 pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
2483 self.buffer_store.read(cx).get_by_path(path, cx)
2484 }
2485
2486 fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
2487 {
2488 let mut remotely_created_models = self.remotely_created_models.lock();
2489 if remotely_created_models.retain_count > 0 {
2490 remotely_created_models.buffers.push(buffer.clone())
2491 }
2492 }
2493
2494 self.request_buffer_diff_recalculation(buffer, cx);
2495
2496 cx.subscribe(buffer, |this, buffer, event, cx| {
2497 this.on_buffer_event(buffer, event, cx);
2498 })
2499 .detach();
2500
2501 Ok(())
2502 }
2503
2504 pub fn open_image(
2505 &mut self,
2506 path: impl Into<ProjectPath>,
2507 cx: &mut Context<Self>,
2508 ) -> Task<Result<Entity<ImageItem>>> {
2509 if self.is_disconnected(cx) {
2510 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2511 }
2512
2513 let open_image_task = self.image_store.update(cx, |image_store, cx| {
2514 image_store.open_image(path.into(), cx)
2515 });
2516
2517 let weak_project = cx.entity().downgrade();
2518 cx.spawn(async move |_, cx| {
2519 let image_item = open_image_task.await?;
2520 let project = weak_project
2521 .upgrade()
2522 .ok_or_else(|| anyhow!("Project dropped"))?;
2523
2524 let metadata = ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
2525 image_item.update(cx, |image_item, cx| {
2526 image_item.image_metadata = Some(metadata);
2527 cx.emit(ImageItemEvent::MetadataUpdated);
2528 })?;
2529
2530 Ok(image_item)
2531 })
2532 }
2533
2534 async fn send_buffer_ordered_messages(
2535 this: WeakEntity<Self>,
2536 rx: UnboundedReceiver<BufferOrderedMessage>,
2537 cx: &mut AsyncApp,
2538 ) -> Result<()> {
2539 const MAX_BATCH_SIZE: usize = 128;
2540
2541 let mut operations_by_buffer_id = HashMap::default();
2542 async fn flush_operations(
2543 this: &WeakEntity<Project>,
2544 operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2545 needs_resync_with_host: &mut bool,
2546 is_local: bool,
2547 cx: &mut AsyncApp,
2548 ) -> Result<()> {
2549 for (buffer_id, operations) in operations_by_buffer_id.drain() {
2550 let request = this.update(cx, |this, _| {
2551 let project_id = this.remote_id()?;
2552 Some(this.client.request(proto::UpdateBuffer {
2553 buffer_id: buffer_id.into(),
2554 project_id,
2555 operations,
2556 }))
2557 })?;
2558 if let Some(request) = request {
2559 if request.await.is_err() && !is_local {
2560 *needs_resync_with_host = true;
2561 break;
2562 }
2563 }
2564 }
2565 Ok(())
2566 }
2567
2568 let mut needs_resync_with_host = false;
2569 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2570
2571 while let Some(changes) = changes.next().await {
2572 let is_local = this.update(cx, |this, _| this.is_local())?;
2573
2574 for change in changes {
2575 match change {
2576 BufferOrderedMessage::Operation {
2577 buffer_id,
2578 operation,
2579 } => {
2580 if needs_resync_with_host {
2581 continue;
2582 }
2583
2584 operations_by_buffer_id
2585 .entry(buffer_id)
2586 .or_insert(Vec::new())
2587 .push(operation);
2588 }
2589
2590 BufferOrderedMessage::Resync => {
2591 operations_by_buffer_id.clear();
2592 if this
2593 .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
2594 .await
2595 .is_ok()
2596 {
2597 needs_resync_with_host = false;
2598 }
2599 }
2600
2601 BufferOrderedMessage::LanguageServerUpdate {
2602 language_server_id,
2603 message,
2604 } => {
2605 flush_operations(
2606 &this,
2607 &mut operations_by_buffer_id,
2608 &mut needs_resync_with_host,
2609 is_local,
2610 cx,
2611 )
2612 .await?;
2613
2614 this.update(cx, |this, _| {
2615 if let Some(project_id) = this.remote_id() {
2616 this.client
2617 .send(proto::UpdateLanguageServer {
2618 project_id,
2619 language_server_id: language_server_id.0 as u64,
2620 variant: Some(message),
2621 })
2622 .log_err();
2623 }
2624 })?;
2625 }
2626 }
2627 }
2628
2629 flush_operations(
2630 &this,
2631 &mut operations_by_buffer_id,
2632 &mut needs_resync_with_host,
2633 is_local,
2634 cx,
2635 )
2636 .await?;
2637 }
2638
2639 Ok(())
2640 }
2641
2642 fn on_buffer_store_event(
2643 &mut self,
2644 _: Entity<BufferStore>,
2645 event: &BufferStoreEvent,
2646 cx: &mut Context<Self>,
2647 ) {
2648 match event {
2649 BufferStoreEvent::BufferAdded(buffer) => {
2650 self.register_buffer(buffer, cx).log_err();
2651 }
2652 BufferStoreEvent::BufferDropped(buffer_id) => {
2653 if let Some(ref ssh_client) = self.ssh_client {
2654 ssh_client
2655 .read(cx)
2656 .proto_client()
2657 .send(proto::CloseBuffer {
2658 project_id: 0,
2659 buffer_id: buffer_id.to_proto(),
2660 })
2661 .log_err();
2662 }
2663 }
2664 _ => {}
2665 }
2666 }
2667
2668 fn on_image_store_event(
2669 &mut self,
2670 _: Entity<ImageStore>,
2671 event: &ImageStoreEvent,
2672 cx: &mut Context<Self>,
2673 ) {
2674 match event {
2675 ImageStoreEvent::ImageAdded(image) => {
2676 cx.subscribe(image, |this, image, event, cx| {
2677 this.on_image_event(image, event, cx);
2678 })
2679 .detach();
2680 }
2681 }
2682 }
2683
2684 fn on_dap_store_event(
2685 &mut self,
2686 _: Entity<DapStore>,
2687 event: &DapStoreEvent,
2688 cx: &mut Context<Self>,
2689 ) {
2690 match event {
2691 DapStoreEvent::Notification(message) => {
2692 cx.emit(Event::Toast {
2693 notification_id: "dap".into(),
2694 message: message.clone(),
2695 });
2696 }
2697 _ => {}
2698 }
2699 }
2700
2701 fn on_lsp_store_event(
2702 &mut self,
2703 _: Entity<LspStore>,
2704 event: &LspStoreEvent,
2705 cx: &mut Context<Self>,
2706 ) {
2707 match event {
2708 LspStoreEvent::DiagnosticsUpdated {
2709 language_server_id,
2710 path,
2711 } => cx.emit(Event::DiagnosticsUpdated {
2712 path: path.clone(),
2713 language_server_id: *language_server_id,
2714 }),
2715 LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2716 Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2717 ),
2718 LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2719 cx.emit(Event::LanguageServerRemoved(*language_server_id))
2720 }
2721 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2722 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2723 ),
2724 LspStoreEvent::LanguageDetected {
2725 buffer,
2726 new_language,
2727 } => {
2728 let Some(_) = new_language else {
2729 cx.emit(Event::LanguageNotFound(buffer.clone()));
2730 return;
2731 };
2732 }
2733 LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2734 LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
2735 LspStoreEvent::LanguageServerPrompt(prompt) => {
2736 cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2737 }
2738 LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2739 cx.emit(Event::DiskBasedDiagnosticsStarted {
2740 language_server_id: *language_server_id,
2741 });
2742 }
2743 LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2744 cx.emit(Event::DiskBasedDiagnosticsFinished {
2745 language_server_id: *language_server_id,
2746 });
2747 }
2748 LspStoreEvent::LanguageServerUpdate {
2749 language_server_id,
2750 message,
2751 } => {
2752 if self.is_local() {
2753 self.enqueue_buffer_ordered_message(
2754 BufferOrderedMessage::LanguageServerUpdate {
2755 language_server_id: *language_server_id,
2756 message: message.clone(),
2757 },
2758 )
2759 .ok();
2760 }
2761 }
2762 LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2763 notification_id: "lsp".into(),
2764 message: message.clone(),
2765 }),
2766 LspStoreEvent::SnippetEdit {
2767 buffer_id,
2768 edits,
2769 most_recent_edit,
2770 } => {
2771 if most_recent_edit.replica_id == self.replica_id() {
2772 cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2773 }
2774 }
2775 }
2776 }
2777
2778 fn on_ssh_event(
2779 &mut self,
2780 _: Entity<SshRemoteClient>,
2781 event: &remote::SshRemoteEvent,
2782 cx: &mut Context<Self>,
2783 ) {
2784 match event {
2785 remote::SshRemoteEvent::Disconnected => {
2786 // if self.is_via_ssh() {
2787 // self.collaborators.clear();
2788 self.worktree_store.update(cx, |store, cx| {
2789 store.disconnected_from_host(cx);
2790 });
2791 self.buffer_store.update(cx, |buffer_store, cx| {
2792 buffer_store.disconnected_from_host(cx)
2793 });
2794 self.lsp_store.update(cx, |lsp_store, _cx| {
2795 lsp_store.disconnected_from_ssh_remote()
2796 });
2797 cx.emit(Event::DisconnectedFromSshRemote);
2798 }
2799 }
2800 }
2801
2802 fn on_settings_observer_event(
2803 &mut self,
2804 _: Entity<SettingsObserver>,
2805 event: &SettingsObserverEvent,
2806 cx: &mut Context<Self>,
2807 ) {
2808 match event {
2809 SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2810 Err(InvalidSettingsError::LocalSettings { message, path }) => {
2811 let message = format!("Failed to set local settings in {path:?}:\n{message}");
2812 cx.emit(Event::Toast {
2813 notification_id: format!("local-settings-{path:?}").into(),
2814 message,
2815 });
2816 }
2817 Ok(path) => cx.emit(Event::HideToast {
2818 notification_id: format!("local-settings-{path:?}").into(),
2819 }),
2820 Err(_) => {}
2821 },
2822 SettingsObserverEvent::LocalTasksUpdated(result) => match result {
2823 Err(InvalidSettingsError::Tasks { message, path }) => {
2824 let message = format!("Failed to set local tasks in {path:?}:\n{message}");
2825 cx.emit(Event::Toast {
2826 notification_id: format!("local-tasks-{path:?}").into(),
2827 message,
2828 });
2829 }
2830 Ok(path) => cx.emit(Event::HideToast {
2831 notification_id: format!("local-tasks-{path:?}").into(),
2832 }),
2833 Err(_) => {}
2834 },
2835 }
2836 }
2837
2838 fn on_worktree_store_event(
2839 &mut self,
2840 _: Entity<WorktreeStore>,
2841 event: &WorktreeStoreEvent,
2842 cx: &mut Context<Self>,
2843 ) {
2844 match event {
2845 WorktreeStoreEvent::WorktreeAdded(worktree) => {
2846 self.on_worktree_added(worktree, cx);
2847 cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
2848 }
2849 WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2850 cx.emit(Event::WorktreeRemoved(*id));
2851 }
2852 WorktreeStoreEvent::WorktreeReleased(_, id) => {
2853 self.on_worktree_released(*id, cx);
2854 }
2855 WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2856 WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2857 WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
2858 self.client()
2859 .telemetry()
2860 .report_discovered_project_events(*worktree_id, changes);
2861 cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
2862 }
2863 WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
2864 cx.emit(Event::DeletedEntry(*worktree_id, *id))
2865 }
2866 // Listen to the GitStore instead.
2867 WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
2868 }
2869 }
2870
2871 fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
2872 let mut remotely_created_models = self.remotely_created_models.lock();
2873 if remotely_created_models.retain_count > 0 {
2874 remotely_created_models.worktrees.push(worktree.clone())
2875 }
2876 }
2877
2878 fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
2879 if let Some(ssh) = &self.ssh_client {
2880 ssh.read(cx)
2881 .proto_client()
2882 .send(proto::RemoveWorktree {
2883 worktree_id: id_to_remove.to_proto(),
2884 })
2885 .log_err();
2886 }
2887 }
2888
2889 fn on_buffer_event(
2890 &mut self,
2891 buffer: Entity<Buffer>,
2892 event: &BufferEvent,
2893 cx: &mut Context<Self>,
2894 ) -> Option<()> {
2895 if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
2896 self.request_buffer_diff_recalculation(&buffer, cx);
2897 }
2898
2899 let buffer_id = buffer.read(cx).remote_id();
2900 match event {
2901 BufferEvent::ReloadNeeded => {
2902 if !self.is_via_collab() {
2903 self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
2904 .detach_and_log_err(cx);
2905 }
2906 }
2907 BufferEvent::Operation {
2908 operation,
2909 is_local: true,
2910 } => {
2911 let operation = language::proto::serialize_operation(operation);
2912
2913 if let Some(ssh) = &self.ssh_client {
2914 ssh.read(cx)
2915 .proto_client()
2916 .send(proto::UpdateBuffer {
2917 project_id: 0,
2918 buffer_id: buffer_id.to_proto(),
2919 operations: vec![operation.clone()],
2920 })
2921 .ok();
2922 }
2923
2924 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2925 buffer_id,
2926 operation,
2927 })
2928 .ok();
2929 }
2930
2931 _ => {}
2932 }
2933
2934 None
2935 }
2936
2937 fn on_image_event(
2938 &mut self,
2939 image: Entity<ImageItem>,
2940 event: &ImageItemEvent,
2941 cx: &mut Context<Self>,
2942 ) -> Option<()> {
2943 match event {
2944 ImageItemEvent::ReloadNeeded => {
2945 if !self.is_via_collab() {
2946 self.reload_images([image.clone()].into_iter().collect(), cx)
2947 .detach_and_log_err(cx);
2948 }
2949 }
2950 _ => {}
2951 }
2952
2953 None
2954 }
2955
2956 fn request_buffer_diff_recalculation(
2957 &mut self,
2958 buffer: &Entity<Buffer>,
2959 cx: &mut Context<Self>,
2960 ) {
2961 self.buffers_needing_diff.insert(buffer.downgrade());
2962 let first_insertion = self.buffers_needing_diff.len() == 1;
2963
2964 let settings = ProjectSettings::get_global(cx);
2965 let delay = if let Some(delay) = settings.git.gutter_debounce {
2966 delay
2967 } else {
2968 if first_insertion {
2969 let this = cx.weak_entity();
2970 cx.defer(move |cx| {
2971 if let Some(this) = this.upgrade() {
2972 this.update(cx, |this, cx| {
2973 this.recalculate_buffer_diffs(cx).detach();
2974 });
2975 }
2976 });
2977 }
2978 return;
2979 };
2980
2981 const MIN_DELAY: u64 = 50;
2982 let delay = delay.max(MIN_DELAY);
2983 let duration = Duration::from_millis(delay);
2984
2985 self.git_diff_debouncer
2986 .fire_new(duration, cx, move |this, cx| {
2987 this.recalculate_buffer_diffs(cx)
2988 });
2989 }
2990
2991 fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
2992 cx.spawn(async move |this, cx| {
2993 loop {
2994 let task = this
2995 .update(cx, |this, cx| {
2996 let buffers = this
2997 .buffers_needing_diff
2998 .drain()
2999 .filter_map(|buffer| buffer.upgrade())
3000 .collect::<Vec<_>>();
3001 if buffers.is_empty() {
3002 None
3003 } else {
3004 Some(this.git_store.update(cx, |git_store, cx| {
3005 git_store.recalculate_buffer_diffs(buffers, cx)
3006 }))
3007 }
3008 })
3009 .ok()
3010 .flatten();
3011
3012 if let Some(task) = task {
3013 task.await;
3014 } else {
3015 break;
3016 }
3017 }
3018 })
3019 }
3020
3021 pub fn set_language_for_buffer(
3022 &mut self,
3023 buffer: &Entity<Buffer>,
3024 new_language: Arc<Language>,
3025 cx: &mut Context<Self>,
3026 ) {
3027 self.lsp_store.update(cx, |lsp_store, cx| {
3028 lsp_store.set_language_for_buffer(buffer, new_language, cx)
3029 })
3030 }
3031
3032 pub fn restart_language_servers_for_buffers(
3033 &mut self,
3034 buffers: Vec<Entity<Buffer>>,
3035 cx: &mut Context<Self>,
3036 ) {
3037 self.lsp_store.update(cx, |lsp_store, cx| {
3038 lsp_store.restart_language_servers_for_buffers(buffers, cx)
3039 })
3040 }
3041
3042 pub fn stop_language_servers_for_buffers(
3043 &mut self,
3044 buffers: Vec<Entity<Buffer>>,
3045 cx: &mut Context<Self>,
3046 ) {
3047 self.lsp_store.update(cx, |lsp_store, cx| {
3048 lsp_store.stop_language_servers_for_buffers(buffers, cx)
3049 })
3050 }
3051
3052 pub fn cancel_language_server_work_for_buffers(
3053 &mut self,
3054 buffers: impl IntoIterator<Item = Entity<Buffer>>,
3055 cx: &mut Context<Self>,
3056 ) {
3057 self.lsp_store.update(cx, |lsp_store, cx| {
3058 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
3059 })
3060 }
3061
3062 pub fn cancel_language_server_work(
3063 &mut self,
3064 server_id: LanguageServerId,
3065 token_to_cancel: Option<String>,
3066 cx: &mut Context<Self>,
3067 ) {
3068 self.lsp_store.update(cx, |lsp_store, cx| {
3069 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
3070 })
3071 }
3072
3073 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3074 self.buffer_ordered_messages_tx
3075 .unbounded_send(message)
3076 .map_err(|e| anyhow!(e))
3077 }
3078
3079 pub fn available_toolchains(
3080 &self,
3081 path: ProjectPath,
3082 language_name: LanguageName,
3083 cx: &App,
3084 ) -> Task<Option<ToolchainList>> {
3085 if let Some(toolchain_store) = self.toolchain_store.clone() {
3086 cx.spawn(async move |cx| {
3087 cx.update(|cx| {
3088 toolchain_store
3089 .read(cx)
3090 .list_toolchains(path, language_name, cx)
3091 })
3092 .ok()?
3093 .await
3094 })
3095 } else {
3096 Task::ready(None)
3097 }
3098 }
3099
3100 pub async fn toolchain_term(
3101 languages: Arc<LanguageRegistry>,
3102 language_name: LanguageName,
3103 ) -> Option<SharedString> {
3104 languages
3105 .language_for_name(language_name.as_ref())
3106 .await
3107 .ok()?
3108 .toolchain_lister()
3109 .map(|lister| lister.term())
3110 }
3111
3112 pub fn toolchain_store(&self) -> Option<Entity<ToolchainStore>> {
3113 self.toolchain_store.clone()
3114 }
3115 pub fn activate_toolchain(
3116 &self,
3117 path: ProjectPath,
3118 toolchain: Toolchain,
3119 cx: &mut App,
3120 ) -> Task<Option<()>> {
3121 let Some(toolchain_store) = self.toolchain_store.clone() else {
3122 return Task::ready(None);
3123 };
3124 toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
3125 }
3126 pub fn active_toolchain(
3127 &self,
3128 path: ProjectPath,
3129 language_name: LanguageName,
3130 cx: &App,
3131 ) -> Task<Option<Toolchain>> {
3132 let Some(toolchain_store) = self.toolchain_store.clone() else {
3133 return Task::ready(None);
3134 };
3135 toolchain_store
3136 .read(cx)
3137 .active_toolchain(path, language_name, cx)
3138 }
3139 pub fn language_server_statuses<'a>(
3140 &'a self,
3141 cx: &'a App,
3142 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
3143 self.lsp_store.read(cx).language_server_statuses()
3144 }
3145
3146 pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
3147 self.lsp_store.read(cx).last_formatting_failure()
3148 }
3149
3150 pub fn reset_last_formatting_failure(&self, cx: &mut App) {
3151 self.lsp_store
3152 .update(cx, |store, _| store.reset_last_formatting_failure());
3153 }
3154
3155 pub fn reload_buffers(
3156 &self,
3157 buffers: HashSet<Entity<Buffer>>,
3158 push_to_history: bool,
3159 cx: &mut Context<Self>,
3160 ) -> Task<Result<ProjectTransaction>> {
3161 self.buffer_store.update(cx, |buffer_store, cx| {
3162 buffer_store.reload_buffers(buffers, push_to_history, cx)
3163 })
3164 }
3165
3166 pub fn reload_images(
3167 &self,
3168 images: HashSet<Entity<ImageItem>>,
3169 cx: &mut Context<Self>,
3170 ) -> Task<Result<()>> {
3171 self.image_store
3172 .update(cx, |image_store, cx| image_store.reload_images(images, cx))
3173 }
3174
3175 pub fn format(
3176 &mut self,
3177 buffers: HashSet<Entity<Buffer>>,
3178 target: LspFormatTarget,
3179 push_to_history: bool,
3180 trigger: lsp_store::FormatTrigger,
3181 cx: &mut Context<Project>,
3182 ) -> Task<anyhow::Result<ProjectTransaction>> {
3183 self.lsp_store.update(cx, |lsp_store, cx| {
3184 lsp_store.format(buffers, target, push_to_history, trigger, cx)
3185 })
3186 }
3187
3188 #[inline(never)]
3189 fn definition_impl(
3190 &mut self,
3191 buffer: &Entity<Buffer>,
3192 position: PointUtf16,
3193 cx: &mut Context<Self>,
3194 ) -> Task<Result<Vec<LocationLink>>> {
3195 self.request_lsp(
3196 buffer.clone(),
3197 LanguageServerToQuery::FirstCapable,
3198 GetDefinition { position },
3199 cx,
3200 )
3201 }
3202 pub fn definition<T: ToPointUtf16>(
3203 &mut self,
3204 buffer: &Entity<Buffer>,
3205 position: T,
3206 cx: &mut Context<Self>,
3207 ) -> Task<Result<Vec<LocationLink>>> {
3208 let position = position.to_point_utf16(buffer.read(cx));
3209 self.definition_impl(buffer, position, cx)
3210 }
3211
3212 fn declaration_impl(
3213 &mut self,
3214 buffer: &Entity<Buffer>,
3215 position: PointUtf16,
3216 cx: &mut Context<Self>,
3217 ) -> Task<Result<Vec<LocationLink>>> {
3218 self.request_lsp(
3219 buffer.clone(),
3220 LanguageServerToQuery::FirstCapable,
3221 GetDeclaration { position },
3222 cx,
3223 )
3224 }
3225
3226 pub fn declaration<T: ToPointUtf16>(
3227 &mut self,
3228 buffer: &Entity<Buffer>,
3229 position: T,
3230 cx: &mut Context<Self>,
3231 ) -> Task<Result<Vec<LocationLink>>> {
3232 let position = position.to_point_utf16(buffer.read(cx));
3233 self.declaration_impl(buffer, position, cx)
3234 }
3235
3236 fn type_definition_impl(
3237 &mut self,
3238 buffer: &Entity<Buffer>,
3239 position: PointUtf16,
3240 cx: &mut Context<Self>,
3241 ) -> Task<Result<Vec<LocationLink>>> {
3242 self.request_lsp(
3243 buffer.clone(),
3244 LanguageServerToQuery::FirstCapable,
3245 GetTypeDefinition { position },
3246 cx,
3247 )
3248 }
3249
3250 pub fn type_definition<T: ToPointUtf16>(
3251 &mut self,
3252 buffer: &Entity<Buffer>,
3253 position: T,
3254 cx: &mut Context<Self>,
3255 ) -> Task<Result<Vec<LocationLink>>> {
3256 let position = position.to_point_utf16(buffer.read(cx));
3257 self.type_definition_impl(buffer, position, cx)
3258 }
3259
3260 pub fn implementation<T: ToPointUtf16>(
3261 &mut self,
3262 buffer: &Entity<Buffer>,
3263 position: T,
3264 cx: &mut Context<Self>,
3265 ) -> Task<Result<Vec<LocationLink>>> {
3266 let position = position.to_point_utf16(buffer.read(cx));
3267 self.request_lsp(
3268 buffer.clone(),
3269 LanguageServerToQuery::FirstCapable,
3270 GetImplementation { position },
3271 cx,
3272 )
3273 }
3274
3275 pub fn references<T: ToPointUtf16>(
3276 &mut self,
3277 buffer: &Entity<Buffer>,
3278 position: T,
3279 cx: &mut Context<Self>,
3280 ) -> Task<Result<Vec<Location>>> {
3281 let position = position.to_point_utf16(buffer.read(cx));
3282 self.request_lsp(
3283 buffer.clone(),
3284 LanguageServerToQuery::FirstCapable,
3285 GetReferences { position },
3286 cx,
3287 )
3288 }
3289
3290 fn document_highlights_impl(
3291 &mut self,
3292 buffer: &Entity<Buffer>,
3293 position: PointUtf16,
3294 cx: &mut Context<Self>,
3295 ) -> Task<Result<Vec<DocumentHighlight>>> {
3296 self.request_lsp(
3297 buffer.clone(),
3298 LanguageServerToQuery::FirstCapable,
3299 GetDocumentHighlights { position },
3300 cx,
3301 )
3302 }
3303
3304 pub fn document_highlights<T: ToPointUtf16>(
3305 &mut self,
3306 buffer: &Entity<Buffer>,
3307 position: T,
3308 cx: &mut Context<Self>,
3309 ) -> Task<Result<Vec<DocumentHighlight>>> {
3310 let position = position.to_point_utf16(buffer.read(cx));
3311 self.document_highlights_impl(buffer, position, cx)
3312 }
3313
3314 pub fn document_symbols(
3315 &mut self,
3316 buffer: &Entity<Buffer>,
3317 cx: &mut Context<Self>,
3318 ) -> Task<Result<Vec<DocumentSymbol>>> {
3319 self.request_lsp(
3320 buffer.clone(),
3321 LanguageServerToQuery::FirstCapable,
3322 GetDocumentSymbols,
3323 cx,
3324 )
3325 }
3326
3327 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
3328 self.lsp_store
3329 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3330 }
3331
3332 pub fn open_buffer_for_symbol(
3333 &mut self,
3334 symbol: &Symbol,
3335 cx: &mut Context<Self>,
3336 ) -> Task<Result<Entity<Buffer>>> {
3337 self.lsp_store.update(cx, |lsp_store, cx| {
3338 lsp_store.open_buffer_for_symbol(symbol, cx)
3339 })
3340 }
3341
3342 pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
3343 let guard = self.retain_remotely_created_models(cx);
3344 let Some(ssh_client) = self.ssh_client.as_ref() else {
3345 return Task::ready(Err(anyhow!("not an ssh project")));
3346 };
3347
3348 let proto_client = ssh_client.read(cx).proto_client();
3349
3350 cx.spawn(async move |project, cx| {
3351 let buffer = proto_client
3352 .request(proto::OpenServerSettings {
3353 project_id: SSH_PROJECT_ID,
3354 })
3355 .await?;
3356
3357 let buffer = project
3358 .update(cx, |project, cx| {
3359 project.buffer_store.update(cx, |buffer_store, cx| {
3360 anyhow::Ok(
3361 buffer_store
3362 .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
3363 )
3364 })
3365 })??
3366 .await;
3367
3368 drop(guard);
3369 buffer
3370 })
3371 }
3372
3373 pub fn open_local_buffer_via_lsp(
3374 &mut self,
3375 abs_path: lsp::Url,
3376 language_server_id: LanguageServerId,
3377 language_server_name: LanguageServerName,
3378 cx: &mut Context<Self>,
3379 ) -> Task<Result<Entity<Buffer>>> {
3380 self.lsp_store.update(cx, |lsp_store, cx| {
3381 lsp_store.open_local_buffer_via_lsp(
3382 abs_path,
3383 language_server_id,
3384 language_server_name,
3385 cx,
3386 )
3387 })
3388 }
3389
3390 pub fn signature_help<T: ToPointUtf16>(
3391 &self,
3392 buffer: &Entity<Buffer>,
3393 position: T,
3394 cx: &mut Context<Self>,
3395 ) -> Task<Vec<SignatureHelp>> {
3396 self.lsp_store.update(cx, |lsp_store, cx| {
3397 lsp_store.signature_help(buffer, position, cx)
3398 })
3399 }
3400
3401 pub fn hover<T: ToPointUtf16>(
3402 &self,
3403 buffer: &Entity<Buffer>,
3404 position: T,
3405 cx: &mut Context<Self>,
3406 ) -> Task<Vec<Hover>> {
3407 let position = position.to_point_utf16(buffer.read(cx));
3408 self.lsp_store
3409 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3410 }
3411
3412 pub fn linked_edit(
3413 &self,
3414 buffer: &Entity<Buffer>,
3415 position: Anchor,
3416 cx: &mut Context<Self>,
3417 ) -> Task<Result<Vec<Range<Anchor>>>> {
3418 self.lsp_store.update(cx, |lsp_store, cx| {
3419 lsp_store.linked_edit(buffer, position, cx)
3420 })
3421 }
3422
3423 pub fn completions<T: ToOffset + ToPointUtf16>(
3424 &self,
3425 buffer: &Entity<Buffer>,
3426 position: T,
3427 context: CompletionContext,
3428 cx: &mut Context<Self>,
3429 ) -> Task<Result<Option<Vec<Completion>>>> {
3430 let position = position.to_point_utf16(buffer.read(cx));
3431 self.lsp_store.update(cx, |lsp_store, cx| {
3432 lsp_store.completions(buffer, position, context, cx)
3433 })
3434 }
3435
3436 pub fn code_actions<T: Clone + ToOffset>(
3437 &mut self,
3438 buffer_handle: &Entity<Buffer>,
3439 range: Range<T>,
3440 kinds: Option<Vec<CodeActionKind>>,
3441 cx: &mut Context<Self>,
3442 ) -> Task<Result<Vec<CodeAction>>> {
3443 let buffer = buffer_handle.read(cx);
3444 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3445 self.lsp_store.update(cx, |lsp_store, cx| {
3446 lsp_store.code_actions(buffer_handle, range, kinds, cx)
3447 })
3448 }
3449
3450 pub fn code_lens<T: Clone + ToOffset>(
3451 &mut self,
3452 buffer_handle: &Entity<Buffer>,
3453 range: Range<T>,
3454 cx: &mut Context<Self>,
3455 ) -> Task<Result<Vec<CodeAction>>> {
3456 let snapshot = buffer_handle.read(cx).snapshot();
3457 let range = snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end);
3458 let code_lens_actions = self
3459 .lsp_store
3460 .update(cx, |lsp_store, cx| lsp_store.code_lens(buffer_handle, cx));
3461
3462 cx.background_spawn(async move {
3463 let mut code_lens_actions = code_lens_actions.await?;
3464 code_lens_actions.retain(|code_lens_action| {
3465 range
3466 .start
3467 .cmp(&code_lens_action.range.start, &snapshot)
3468 .is_ge()
3469 && range
3470 .end
3471 .cmp(&code_lens_action.range.end, &snapshot)
3472 .is_le()
3473 });
3474 Ok(code_lens_actions)
3475 })
3476 }
3477
3478 pub fn apply_code_action(
3479 &self,
3480 buffer_handle: Entity<Buffer>,
3481 action: CodeAction,
3482 push_to_history: bool,
3483 cx: &mut Context<Self>,
3484 ) -> Task<Result<ProjectTransaction>> {
3485 self.lsp_store.update(cx, |lsp_store, cx| {
3486 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3487 })
3488 }
3489
3490 pub fn apply_code_action_kind(
3491 &self,
3492 buffers: HashSet<Entity<Buffer>>,
3493 kind: CodeActionKind,
3494 push_to_history: bool,
3495 cx: &mut Context<Self>,
3496 ) -> Task<Result<ProjectTransaction>> {
3497 self.lsp_store.update(cx, |lsp_store, cx| {
3498 lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
3499 })
3500 }
3501
3502 fn prepare_rename_impl(
3503 &mut self,
3504 buffer: Entity<Buffer>,
3505 position: PointUtf16,
3506 cx: &mut Context<Self>,
3507 ) -> Task<Result<PrepareRenameResponse>> {
3508 self.request_lsp(
3509 buffer,
3510 LanguageServerToQuery::FirstCapable,
3511 PrepareRename { position },
3512 cx,
3513 )
3514 }
3515 pub fn prepare_rename<T: ToPointUtf16>(
3516 &mut self,
3517 buffer: Entity<Buffer>,
3518 position: T,
3519 cx: &mut Context<Self>,
3520 ) -> Task<Result<PrepareRenameResponse>> {
3521 let position = position.to_point_utf16(buffer.read(cx));
3522 self.prepare_rename_impl(buffer, position, cx)
3523 }
3524
3525 pub fn perform_rename<T: ToPointUtf16>(
3526 &mut self,
3527 buffer: Entity<Buffer>,
3528 position: T,
3529 new_name: String,
3530 cx: &mut Context<Self>,
3531 ) -> Task<Result<ProjectTransaction>> {
3532 let push_to_history = true;
3533 let position = position.to_point_utf16(buffer.read(cx));
3534 self.request_lsp(
3535 buffer,
3536 LanguageServerToQuery::FirstCapable,
3537 PerformRename {
3538 position,
3539 new_name,
3540 push_to_history,
3541 },
3542 cx,
3543 )
3544 }
3545
3546 pub fn on_type_format<T: ToPointUtf16>(
3547 &mut self,
3548 buffer: Entity<Buffer>,
3549 position: T,
3550 trigger: String,
3551 push_to_history: bool,
3552 cx: &mut Context<Self>,
3553 ) -> Task<Result<Option<Transaction>>> {
3554 self.lsp_store.update(cx, |lsp_store, cx| {
3555 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3556 })
3557 }
3558
3559 pub fn inline_values(
3560 &mut self,
3561 session: Entity<Session>,
3562 active_stack_frame: ActiveStackFrame,
3563 buffer_handle: Entity<Buffer>,
3564 range: Range<text::Anchor>,
3565 cx: &mut Context<Self>,
3566 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3567 let language_name = buffer_handle
3568 .read(cx)
3569 .language()
3570 .map(|language| language.name().to_string());
3571
3572 let Some(inline_value_provider) = language_name
3573 .and_then(|language| DapRegistry::global(cx).inline_value_provider(&language))
3574 else {
3575 return Task::ready(Err(anyhow::anyhow!("Inline value provider not found")));
3576 };
3577
3578 let snapshot = buffer_handle.read(cx).snapshot();
3579
3580 let root_node = snapshot.syntax_root_ancestor(range.end).unwrap();
3581
3582 let row = snapshot
3583 .summary_for_anchor::<text::PointUtf16>(&range.end)
3584 .row as usize;
3585
3586 let inline_value_locations = inline_value_provider.provide(
3587 root_node,
3588 snapshot
3589 .text_for_range(Anchor::MIN..range.end)
3590 .collect::<String>()
3591 .as_str(),
3592 row,
3593 );
3594
3595 let stack_frame_id = active_stack_frame.stack_frame_id;
3596 cx.spawn(async move |this, cx| {
3597 this.update(cx, |project, cx| {
3598 project.dap_store().update(cx, |dap_store, cx| {
3599 dap_store.resolve_inline_value_locations(
3600 session,
3601 stack_frame_id,
3602 buffer_handle,
3603 inline_value_locations,
3604 cx,
3605 )
3606 })
3607 })?
3608 .await
3609 })
3610 }
3611
3612 pub fn inlay_hints<T: ToOffset>(
3613 &mut self,
3614 buffer_handle: Entity<Buffer>,
3615 range: Range<T>,
3616 cx: &mut Context<Self>,
3617 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3618 let buffer = buffer_handle.read(cx);
3619 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3620 self.lsp_store.update(cx, |lsp_store, cx| {
3621 lsp_store.inlay_hints(buffer_handle, range, cx)
3622 })
3623 }
3624
3625 pub fn resolve_inlay_hint(
3626 &self,
3627 hint: InlayHint,
3628 buffer_handle: Entity<Buffer>,
3629 server_id: LanguageServerId,
3630 cx: &mut Context<Self>,
3631 ) -> Task<anyhow::Result<InlayHint>> {
3632 self.lsp_store.update(cx, |lsp_store, cx| {
3633 lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3634 })
3635 }
3636
3637 pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
3638 let (result_tx, result_rx) = smol::channel::unbounded();
3639
3640 let matching_buffers_rx = if query.is_opened_only() {
3641 self.sort_search_candidates(&query, cx)
3642 } else {
3643 self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3644 };
3645
3646 cx.spawn(async move |_, cx| {
3647 let mut range_count = 0;
3648 let mut buffer_count = 0;
3649 let mut limit_reached = false;
3650 let query = Arc::new(query);
3651 let mut chunks = matching_buffers_rx.ready_chunks(64);
3652
3653 // Now that we know what paths match the query, we will load at most
3654 // 64 buffers at a time to avoid overwhelming the main thread. For each
3655 // opened buffer, we will spawn a background task that retrieves all the
3656 // ranges in the buffer matched by the query.
3657 let mut chunks = pin!(chunks);
3658 'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3659 let mut chunk_results = Vec::new();
3660 for buffer in matching_buffer_chunk {
3661 let buffer = buffer.clone();
3662 let query = query.clone();
3663 let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot())?;
3664 chunk_results.push(cx.background_spawn(async move {
3665 let ranges = query
3666 .search(&snapshot, None)
3667 .await
3668 .iter()
3669 .map(|range| {
3670 snapshot.anchor_before(range.start)
3671 ..snapshot.anchor_after(range.end)
3672 })
3673 .collect::<Vec<_>>();
3674 anyhow::Ok((buffer, ranges))
3675 }));
3676 }
3677
3678 let chunk_results = futures::future::join_all(chunk_results).await;
3679 for result in chunk_results {
3680 if let Some((buffer, ranges)) = result.log_err() {
3681 range_count += ranges.len();
3682 buffer_count += 1;
3683 result_tx
3684 .send(SearchResult::Buffer { buffer, ranges })
3685 .await?;
3686 if buffer_count > MAX_SEARCH_RESULT_FILES
3687 || range_count > MAX_SEARCH_RESULT_RANGES
3688 {
3689 limit_reached = true;
3690 break 'outer;
3691 }
3692 }
3693 }
3694 }
3695
3696 if limit_reached {
3697 result_tx.send(SearchResult::LimitReached).await?;
3698 }
3699
3700 anyhow::Ok(())
3701 })
3702 .detach();
3703
3704 result_rx
3705 }
3706
3707 fn find_search_candidate_buffers(
3708 &mut self,
3709 query: &SearchQuery,
3710 limit: usize,
3711 cx: &mut Context<Project>,
3712 ) -> Receiver<Entity<Buffer>> {
3713 if self.is_local() {
3714 let fs = self.fs.clone();
3715 self.buffer_store.update(cx, |buffer_store, cx| {
3716 buffer_store.find_search_candidates(query, limit, fs, cx)
3717 })
3718 } else {
3719 self.find_search_candidates_remote(query, limit, cx)
3720 }
3721 }
3722
3723 fn sort_search_candidates(
3724 &mut self,
3725 search_query: &SearchQuery,
3726 cx: &mut Context<Project>,
3727 ) -> Receiver<Entity<Buffer>> {
3728 let worktree_store = self.worktree_store.read(cx);
3729 let mut buffers = search_query
3730 .buffers()
3731 .into_iter()
3732 .flatten()
3733 .filter(|buffer| {
3734 let b = buffer.read(cx);
3735 if let Some(file) = b.file() {
3736 if !search_query.match_path(file.path()) {
3737 return false;
3738 }
3739 if let Some(entry) = b
3740 .entry_id(cx)
3741 .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3742 {
3743 if entry.is_ignored && !search_query.include_ignored() {
3744 return false;
3745 }
3746 }
3747 }
3748 true
3749 })
3750 .collect::<Vec<_>>();
3751 let (tx, rx) = smol::channel::unbounded();
3752 buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3753 (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3754 (None, Some(_)) => std::cmp::Ordering::Less,
3755 (Some(_), None) => std::cmp::Ordering::Greater,
3756 (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3757 });
3758 for buffer in buffers {
3759 tx.send_blocking(buffer.clone()).unwrap()
3760 }
3761
3762 rx
3763 }
3764
3765 fn find_search_candidates_remote(
3766 &mut self,
3767 query: &SearchQuery,
3768 limit: usize,
3769 cx: &mut Context<Project>,
3770 ) -> Receiver<Entity<Buffer>> {
3771 let (tx, rx) = smol::channel::unbounded();
3772
3773 let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3774 (ssh_client.read(cx).proto_client(), 0)
3775 } else if let Some(remote_id) = self.remote_id() {
3776 (self.client.clone().into(), remote_id)
3777 } else {
3778 return rx;
3779 };
3780
3781 let request = client.request(proto::FindSearchCandidates {
3782 project_id: remote_id,
3783 query: Some(query.to_proto()),
3784 limit: limit as _,
3785 });
3786 let guard = self.retain_remotely_created_models(cx);
3787
3788 cx.spawn(async move |project, cx| {
3789 let response = request.await?;
3790 for buffer_id in response.buffer_ids {
3791 let buffer_id = BufferId::new(buffer_id)?;
3792 let buffer = project
3793 .update(cx, |project, cx| {
3794 project.buffer_store.update(cx, |buffer_store, cx| {
3795 buffer_store.wait_for_remote_buffer(buffer_id, cx)
3796 })
3797 })?
3798 .await?;
3799 let _ = tx.send(buffer).await;
3800 }
3801
3802 drop(guard);
3803 anyhow::Ok(())
3804 })
3805 .detach_and_log_err(cx);
3806 rx
3807 }
3808
3809 pub fn request_lsp<R: LspCommand>(
3810 &mut self,
3811 buffer_handle: Entity<Buffer>,
3812 server: LanguageServerToQuery,
3813 request: R,
3814 cx: &mut Context<Self>,
3815 ) -> Task<Result<R::Response>>
3816 where
3817 <R::LspRequest as lsp::request::Request>::Result: Send,
3818 <R::LspRequest as lsp::request::Request>::Params: Send,
3819 {
3820 let guard = self.retain_remotely_created_models(cx);
3821 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3822 lsp_store.request_lsp(buffer_handle, server, request, cx)
3823 });
3824 cx.spawn(async move |_, _| {
3825 let result = task.await;
3826 drop(guard);
3827 result
3828 })
3829 }
3830
3831 /// Move a worktree to a new position in the worktree order.
3832 ///
3833 /// The worktree will moved to the opposite side of the destination worktree.
3834 ///
3835 /// # Example
3836 ///
3837 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3838 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3839 ///
3840 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3841 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3842 ///
3843 /// # Errors
3844 ///
3845 /// An error will be returned if the worktree or destination worktree are not found.
3846 pub fn move_worktree(
3847 &mut self,
3848 source: WorktreeId,
3849 destination: WorktreeId,
3850 cx: &mut Context<Self>,
3851 ) -> Result<()> {
3852 self.worktree_store.update(cx, |worktree_store, cx| {
3853 worktree_store.move_worktree(source, destination, cx)
3854 })
3855 }
3856
3857 pub fn find_or_create_worktree(
3858 &mut self,
3859 abs_path: impl AsRef<Path>,
3860 visible: bool,
3861 cx: &mut Context<Self>,
3862 ) -> Task<Result<(Entity<Worktree>, PathBuf)>> {
3863 self.worktree_store.update(cx, |worktree_store, cx| {
3864 worktree_store.find_or_create_worktree(abs_path, visible, cx)
3865 })
3866 }
3867
3868 pub fn find_worktree(&self, abs_path: &Path, cx: &App) -> Option<(Entity<Worktree>, PathBuf)> {
3869 self.worktree_store.read_with(cx, |worktree_store, cx| {
3870 worktree_store.find_worktree(abs_path, cx)
3871 })
3872 }
3873
3874 pub fn is_shared(&self) -> bool {
3875 match &self.client_state {
3876 ProjectClientState::Shared { .. } => true,
3877 ProjectClientState::Local => false,
3878 ProjectClientState::Remote { .. } => true,
3879 }
3880 }
3881
3882 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3883 pub fn resolve_path_in_buffer(
3884 &self,
3885 path: &str,
3886 buffer: &Entity<Buffer>,
3887 cx: &mut Context<Self>,
3888 ) -> Task<Option<ResolvedPath>> {
3889 let path_buf = PathBuf::from(path);
3890 if path_buf.is_absolute() || path.starts_with("~") {
3891 self.resolve_abs_path(path, cx)
3892 } else {
3893 self.resolve_path_in_worktrees(path_buf, buffer, cx)
3894 }
3895 }
3896
3897 pub fn resolve_abs_file_path(
3898 &self,
3899 path: &str,
3900 cx: &mut Context<Self>,
3901 ) -> Task<Option<ResolvedPath>> {
3902 let resolve_task = self.resolve_abs_path(path, cx);
3903 cx.background_spawn(async move {
3904 let resolved_path = resolve_task.await;
3905 resolved_path.filter(|path| path.is_file())
3906 })
3907 }
3908
3909 pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
3910 if self.is_local() {
3911 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3912 let fs = self.fs.clone();
3913 cx.background_spawn(async move {
3914 let path = expanded.as_path();
3915 let metadata = fs.metadata(path).await.ok().flatten();
3916
3917 metadata.map(|metadata| ResolvedPath::AbsPath {
3918 path: expanded,
3919 is_dir: metadata.is_dir,
3920 })
3921 })
3922 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3923 let request_path = Path::new(path);
3924 let request = ssh_client
3925 .read(cx)
3926 .proto_client()
3927 .request(proto::GetPathMetadata {
3928 project_id: SSH_PROJECT_ID,
3929 path: request_path.to_proto(),
3930 });
3931 cx.background_spawn(async move {
3932 let response = request.await.log_err()?;
3933 if response.exists {
3934 Some(ResolvedPath::AbsPath {
3935 path: PathBuf::from_proto(response.path),
3936 is_dir: response.is_dir,
3937 })
3938 } else {
3939 None
3940 }
3941 })
3942 } else {
3943 return Task::ready(None);
3944 }
3945 }
3946
3947 fn resolve_path_in_worktrees(
3948 &self,
3949 path: PathBuf,
3950 buffer: &Entity<Buffer>,
3951 cx: &mut Context<Self>,
3952 ) -> Task<Option<ResolvedPath>> {
3953 let mut candidates = vec![path.clone()];
3954
3955 if let Some(file) = buffer.read(cx).file() {
3956 if let Some(dir) = file.path().parent() {
3957 let joined = dir.to_path_buf().join(path);
3958 candidates.push(joined);
3959 }
3960 }
3961
3962 let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
3963 let worktrees_with_ids: Vec<_> = self
3964 .worktrees(cx)
3965 .map(|worktree| {
3966 let id = worktree.read(cx).id();
3967 (worktree, id)
3968 })
3969 .collect();
3970
3971 cx.spawn(async move |_, mut cx| {
3972 if let Some(buffer_worktree_id) = buffer_worktree_id {
3973 if let Some((worktree, _)) = worktrees_with_ids
3974 .iter()
3975 .find(|(_, id)| *id == buffer_worktree_id)
3976 {
3977 for candidate in candidates.iter() {
3978 if let Some(path) =
3979 Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3980 {
3981 return Some(path);
3982 }
3983 }
3984 }
3985 }
3986 for (worktree, id) in worktrees_with_ids {
3987 if Some(id) == buffer_worktree_id {
3988 continue;
3989 }
3990 for candidate in candidates.iter() {
3991 if let Some(path) =
3992 Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3993 {
3994 return Some(path);
3995 }
3996 }
3997 }
3998 None
3999 })
4000 }
4001
4002 fn resolve_path_in_worktree(
4003 worktree: &Entity<Worktree>,
4004 path: &PathBuf,
4005 cx: &mut AsyncApp,
4006 ) -> Option<ResolvedPath> {
4007 worktree
4008 .update(cx, |worktree, _| {
4009 let root_entry_path = &worktree.root_entry()?.path;
4010 let resolved = resolve_path(root_entry_path, path);
4011 let stripped = resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
4012 worktree.entry_for_path(stripped).map(|entry| {
4013 let project_path = ProjectPath {
4014 worktree_id: worktree.id(),
4015 path: entry.path.clone(),
4016 };
4017 ResolvedPath::ProjectPath {
4018 project_path,
4019 is_dir: entry.is_dir(),
4020 }
4021 })
4022 })
4023 .ok()?
4024 }
4025
4026 pub fn list_directory(
4027 &self,
4028 query: String,
4029 cx: &mut Context<Self>,
4030 ) -> Task<Result<Vec<DirectoryItem>>> {
4031 if self.is_local() {
4032 DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
4033 } else if let Some(session) = self.ssh_client.as_ref() {
4034 let path_buf = PathBuf::from(query);
4035 let request = proto::ListRemoteDirectory {
4036 dev_server_id: SSH_PROJECT_ID,
4037 path: path_buf.to_proto(),
4038 config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4039 };
4040
4041 let response = session.read(cx).proto_client().request(request);
4042 cx.background_spawn(async move {
4043 let proto::ListRemoteDirectoryResponse {
4044 entries,
4045 entry_info,
4046 } = response.await?;
4047 Ok(entries
4048 .into_iter()
4049 .zip(entry_info)
4050 .map(|(entry, info)| DirectoryItem {
4051 path: PathBuf::from(entry),
4052 is_dir: info.is_dir,
4053 })
4054 .collect())
4055 })
4056 } else {
4057 Task::ready(Err(anyhow!("cannot list directory in remote project")))
4058 }
4059 }
4060
4061 pub fn create_worktree(
4062 &mut self,
4063 abs_path: impl AsRef<Path>,
4064 visible: bool,
4065 cx: &mut Context<Self>,
4066 ) -> Task<Result<Entity<Worktree>>> {
4067 self.worktree_store.update(cx, |worktree_store, cx| {
4068 worktree_store.create_worktree(abs_path, visible, cx)
4069 })
4070 }
4071
4072 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4073 self.worktree_store.update(cx, |worktree_store, cx| {
4074 worktree_store.remove_worktree(id_to_remove, cx);
4075 });
4076 }
4077
4078 fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4079 self.worktree_store.update(cx, |worktree_store, cx| {
4080 worktree_store.add(worktree, cx);
4081 });
4082 }
4083
4084 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4085 let new_active_entry = entry.and_then(|project_path| {
4086 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4087 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4088 Some(entry.id)
4089 });
4090 if new_active_entry != self.active_entry {
4091 self.active_entry = new_active_entry;
4092 self.lsp_store.update(cx, |lsp_store, _| {
4093 lsp_store.set_active_entry(new_active_entry);
4094 });
4095 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4096 }
4097 }
4098
4099 pub fn language_servers_running_disk_based_diagnostics<'a>(
4100 &'a self,
4101 cx: &'a App,
4102 ) -> impl Iterator<Item = LanguageServerId> + 'a {
4103 self.lsp_store
4104 .read(cx)
4105 .language_servers_running_disk_based_diagnostics()
4106 }
4107
4108 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4109 self.lsp_store
4110 .read(cx)
4111 .diagnostic_summary(include_ignored, cx)
4112 }
4113
4114 pub fn diagnostic_summaries<'a>(
4115 &'a self,
4116 include_ignored: bool,
4117 cx: &'a App,
4118 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4119 self.lsp_store
4120 .read(cx)
4121 .diagnostic_summaries(include_ignored, cx)
4122 }
4123
4124 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4125 self.active_entry
4126 }
4127
4128 pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
4129 self.worktree_store.read(cx).entry_for_path(path, cx)
4130 }
4131
4132 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4133 let worktree = self.worktree_for_entry(entry_id, cx)?;
4134 let worktree = worktree.read(cx);
4135 let worktree_id = worktree.id();
4136 let path = worktree.entry_for_id(entry_id)?.path.clone();
4137 Some(ProjectPath { worktree_id, path })
4138 }
4139
4140 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4141 self.worktree_for_id(project_path.worktree_id, cx)?
4142 .read(cx)
4143 .absolutize(&project_path.path)
4144 .ok()
4145 }
4146
4147 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4148 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4149 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4150 /// the first visible worktree that has an entry for that relative path.
4151 ///
4152 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4153 /// root name from paths.
4154 ///
4155 /// # Arguments
4156 ///
4157 /// * `path` - A full path that starts with a worktree root name, or alternatively a
4158 /// relative path within a visible worktree.
4159 /// * `cx` - A reference to the `AppContext`.
4160 ///
4161 /// # Returns
4162 ///
4163 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4164 pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4165 let path = path.as_ref();
4166 let worktree_store = self.worktree_store.read(cx);
4167
4168 if path.is_absolute() {
4169 for worktree in worktree_store.visible_worktrees(cx) {
4170 let worktree_abs_path = worktree.read(cx).abs_path();
4171
4172 if let Ok(relative_path) = path.strip_prefix(worktree_abs_path) {
4173 return Some(ProjectPath {
4174 worktree_id: worktree.read(cx).id(),
4175 path: relative_path.into(),
4176 });
4177 }
4178 }
4179 } else {
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
4201 None
4202 }
4203
4204 pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4205 self.find_worktree(abs_path, cx)
4206 .map(|(worktree, relative_path)| ProjectPath {
4207 worktree_id: worktree.read(cx).id(),
4208 path: relative_path.into(),
4209 })
4210 }
4211
4212 pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4213 Some(
4214 self.worktree_for_id(project_path.worktree_id, cx)?
4215 .read(cx)
4216 .abs_path()
4217 .to_path_buf(),
4218 )
4219 }
4220
4221 pub fn blame_buffer(
4222 &self,
4223 buffer: &Entity<Buffer>,
4224 version: Option<clock::Global>,
4225 cx: &mut App,
4226 ) -> Task<Result<Option<Blame>>> {
4227 self.git_store.update(cx, |git_store, cx| {
4228 git_store.blame_buffer(buffer, version, cx)
4229 })
4230 }
4231
4232 pub fn get_permalink_to_line(
4233 &self,
4234 buffer: &Entity<Buffer>,
4235 selection: Range<u32>,
4236 cx: &mut App,
4237 ) -> Task<Result<url::Url>> {
4238 self.git_store.update(cx, |git_store, cx| {
4239 git_store.get_permalink_to_line(buffer, selection, cx)
4240 })
4241 }
4242
4243 // RPC message handlers
4244
4245 async fn handle_unshare_project(
4246 this: Entity<Self>,
4247 _: TypedEnvelope<proto::UnshareProject>,
4248 mut cx: AsyncApp,
4249 ) -> Result<()> {
4250 this.update(&mut cx, |this, cx| {
4251 if this.is_local() || this.is_via_ssh() {
4252 this.unshare(cx)?;
4253 } else {
4254 this.disconnected_from_host(cx);
4255 }
4256 Ok(())
4257 })?
4258 }
4259
4260 async fn handle_add_collaborator(
4261 this: Entity<Self>,
4262 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4263 mut cx: AsyncApp,
4264 ) -> Result<()> {
4265 let collaborator = envelope
4266 .payload
4267 .collaborator
4268 .take()
4269 .ok_or_else(|| anyhow!("empty collaborator"))?;
4270
4271 let collaborator = Collaborator::from_proto(collaborator)?;
4272 this.update(&mut cx, |this, cx| {
4273 this.buffer_store.update(cx, |buffer_store, _| {
4274 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4275 });
4276 this.breakpoint_store.read(cx).broadcast();
4277 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4278 this.collaborators
4279 .insert(collaborator.peer_id, collaborator);
4280 })?;
4281
4282 Ok(())
4283 }
4284
4285 async fn handle_update_project_collaborator(
4286 this: Entity<Self>,
4287 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4288 mut cx: AsyncApp,
4289 ) -> Result<()> {
4290 let old_peer_id = envelope
4291 .payload
4292 .old_peer_id
4293 .ok_or_else(|| anyhow!("missing old peer id"))?;
4294 let new_peer_id = envelope
4295 .payload
4296 .new_peer_id
4297 .ok_or_else(|| anyhow!("missing new peer id"))?;
4298 this.update(&mut cx, |this, cx| {
4299 let collaborator = this
4300 .collaborators
4301 .remove(&old_peer_id)
4302 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4303 let is_host = collaborator.is_host;
4304 this.collaborators.insert(new_peer_id, collaborator);
4305
4306 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4307 this.buffer_store.update(cx, |buffer_store, _| {
4308 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4309 });
4310
4311 if is_host {
4312 this.buffer_store
4313 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4314 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4315 .unwrap();
4316 cx.emit(Event::HostReshared);
4317 }
4318
4319 cx.emit(Event::CollaboratorUpdated {
4320 old_peer_id,
4321 new_peer_id,
4322 });
4323 Ok(())
4324 })?
4325 }
4326
4327 async fn handle_remove_collaborator(
4328 this: Entity<Self>,
4329 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4330 mut cx: AsyncApp,
4331 ) -> Result<()> {
4332 this.update(&mut cx, |this, cx| {
4333 let peer_id = envelope
4334 .payload
4335 .peer_id
4336 .ok_or_else(|| anyhow!("invalid peer id"))?;
4337 let replica_id = this
4338 .collaborators
4339 .remove(&peer_id)
4340 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4341 .replica_id;
4342 this.buffer_store.update(cx, |buffer_store, cx| {
4343 buffer_store.forget_shared_buffers_for(&peer_id);
4344 for buffer in buffer_store.buffers() {
4345 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4346 }
4347 });
4348 this.git_store.update(cx, |git_store, _| {
4349 git_store.forget_shared_diffs_for(&peer_id);
4350 });
4351
4352 cx.emit(Event::CollaboratorLeft(peer_id));
4353 Ok(())
4354 })?
4355 }
4356
4357 async fn handle_update_project(
4358 this: Entity<Self>,
4359 envelope: TypedEnvelope<proto::UpdateProject>,
4360 mut cx: AsyncApp,
4361 ) -> Result<()> {
4362 this.update(&mut cx, |this, cx| {
4363 // Don't handle messages that were sent before the response to us joining the project
4364 if envelope.message_id > this.join_project_response_message_id {
4365 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4366 }
4367 Ok(())
4368 })?
4369 }
4370
4371 async fn handle_toast(
4372 this: Entity<Self>,
4373 envelope: TypedEnvelope<proto::Toast>,
4374 mut cx: AsyncApp,
4375 ) -> Result<()> {
4376 this.update(&mut cx, |_, cx| {
4377 cx.emit(Event::Toast {
4378 notification_id: envelope.payload.notification_id.into(),
4379 message: envelope.payload.message,
4380 });
4381 Ok(())
4382 })?
4383 }
4384
4385 async fn handle_language_server_prompt_request(
4386 this: Entity<Self>,
4387 envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4388 mut cx: AsyncApp,
4389 ) -> Result<proto::LanguageServerPromptResponse> {
4390 let (tx, mut rx) = smol::channel::bounded(1);
4391 let actions: Vec<_> = envelope
4392 .payload
4393 .actions
4394 .into_iter()
4395 .map(|action| MessageActionItem {
4396 title: action,
4397 properties: Default::default(),
4398 })
4399 .collect();
4400 this.update(&mut cx, |_, cx| {
4401 cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4402 level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4403 message: envelope.payload.message,
4404 actions: actions.clone(),
4405 lsp_name: envelope.payload.lsp_name,
4406 response_channel: tx,
4407 }));
4408
4409 anyhow::Ok(())
4410 })??;
4411
4412 // We drop `this` to avoid holding a reference in this future for too
4413 // long.
4414 // If we keep the reference, we might not drop the `Project` early
4415 // enough when closing a window and it will only get releases on the
4416 // next `flush_effects()` call.
4417 drop(this);
4418
4419 let mut rx = pin!(rx);
4420 let answer = rx.next().await;
4421
4422 Ok(LanguageServerPromptResponse {
4423 action_response: answer.and_then(|answer| {
4424 actions
4425 .iter()
4426 .position(|action| *action == answer)
4427 .map(|index| index as u64)
4428 }),
4429 })
4430 }
4431
4432 async fn handle_hide_toast(
4433 this: Entity<Self>,
4434 envelope: TypedEnvelope<proto::HideToast>,
4435 mut cx: AsyncApp,
4436 ) -> Result<()> {
4437 this.update(&mut cx, |_, cx| {
4438 cx.emit(Event::HideToast {
4439 notification_id: envelope.payload.notification_id.into(),
4440 });
4441 Ok(())
4442 })?
4443 }
4444
4445 // Collab sends UpdateWorktree protos as messages
4446 async fn handle_update_worktree(
4447 this: Entity<Self>,
4448 envelope: TypedEnvelope<proto::UpdateWorktree>,
4449 mut cx: AsyncApp,
4450 ) -> Result<()> {
4451 this.update(&mut cx, |this, cx| {
4452 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4453 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4454 worktree.update(cx, |worktree, _| {
4455 let worktree = worktree.as_remote_mut().unwrap();
4456 worktree.update_from_remote(envelope.payload);
4457 });
4458 }
4459 Ok(())
4460 })?
4461 }
4462
4463 async fn handle_update_buffer_from_ssh(
4464 this: Entity<Self>,
4465 envelope: TypedEnvelope<proto::UpdateBuffer>,
4466 cx: AsyncApp,
4467 ) -> Result<proto::Ack> {
4468 let buffer_store = this.read_with(&cx, |this, cx| {
4469 if let Some(remote_id) = this.remote_id() {
4470 let mut payload = envelope.payload.clone();
4471 payload.project_id = remote_id;
4472 cx.background_spawn(this.client.request(payload))
4473 .detach_and_log_err(cx);
4474 }
4475 this.buffer_store.clone()
4476 })?;
4477 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4478 }
4479
4480 async fn handle_update_buffer(
4481 this: Entity<Self>,
4482 envelope: TypedEnvelope<proto::UpdateBuffer>,
4483 cx: AsyncApp,
4484 ) -> Result<proto::Ack> {
4485 let buffer_store = this.read_with(&cx, |this, cx| {
4486 if let Some(ssh) = &this.ssh_client {
4487 let mut payload = envelope.payload.clone();
4488 payload.project_id = SSH_PROJECT_ID;
4489 cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4490 .detach_and_log_err(cx);
4491 }
4492 this.buffer_store.clone()
4493 })?;
4494 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4495 }
4496
4497 fn retain_remotely_created_models(
4498 &mut self,
4499 cx: &mut Context<Self>,
4500 ) -> RemotelyCreatedModelGuard {
4501 {
4502 let mut remotely_create_models = self.remotely_created_models.lock();
4503 if remotely_create_models.retain_count == 0 {
4504 remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
4505 remotely_create_models.worktrees =
4506 self.worktree_store.read(cx).worktrees().collect();
4507 }
4508 remotely_create_models.retain_count += 1;
4509 }
4510 RemotelyCreatedModelGuard {
4511 remote_models: Arc::downgrade(&self.remotely_created_models),
4512 }
4513 }
4514
4515 async fn handle_create_buffer_for_peer(
4516 this: Entity<Self>,
4517 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4518 mut cx: AsyncApp,
4519 ) -> Result<()> {
4520 this.update(&mut cx, |this, cx| {
4521 this.buffer_store.update(cx, |buffer_store, cx| {
4522 buffer_store.handle_create_buffer_for_peer(
4523 envelope,
4524 this.replica_id(),
4525 this.capability(),
4526 cx,
4527 )
4528 })
4529 })?
4530 }
4531
4532 async fn handle_synchronize_buffers(
4533 this: Entity<Self>,
4534 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4535 mut cx: AsyncApp,
4536 ) -> Result<proto::SynchronizeBuffersResponse> {
4537 let response = this.update(&mut cx, |this, cx| {
4538 let client = this.client.clone();
4539 this.buffer_store.update(cx, |this, cx| {
4540 this.handle_synchronize_buffers(envelope, cx, client)
4541 })
4542 })??;
4543
4544 Ok(response)
4545 }
4546
4547 async fn handle_search_candidate_buffers(
4548 this: Entity<Self>,
4549 envelope: TypedEnvelope<proto::FindSearchCandidates>,
4550 mut cx: AsyncApp,
4551 ) -> Result<proto::FindSearchCandidatesResponse> {
4552 let peer_id = envelope.original_sender_id()?;
4553 let message = envelope.payload;
4554 let query = SearchQuery::from_proto(
4555 message
4556 .query
4557 .ok_or_else(|| anyhow!("missing query field"))?,
4558 )?;
4559 let results = this.update(&mut cx, |this, cx| {
4560 this.find_search_candidate_buffers(&query, message.limit as _, cx)
4561 })?;
4562
4563 let mut response = proto::FindSearchCandidatesResponse {
4564 buffer_ids: Vec::new(),
4565 };
4566
4567 while let Ok(buffer) = results.recv().await {
4568 this.update(&mut cx, |this, cx| {
4569 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4570 response.buffer_ids.push(buffer_id.to_proto());
4571 })?;
4572 }
4573
4574 Ok(response)
4575 }
4576
4577 async fn handle_open_buffer_by_id(
4578 this: Entity<Self>,
4579 envelope: TypedEnvelope<proto::OpenBufferById>,
4580 mut cx: AsyncApp,
4581 ) -> Result<proto::OpenBufferResponse> {
4582 let peer_id = envelope.original_sender_id()?;
4583 let buffer_id = BufferId::new(envelope.payload.id)?;
4584 let buffer = this
4585 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4586 .await?;
4587 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4588 }
4589
4590 async fn handle_open_buffer_by_path(
4591 this: Entity<Self>,
4592 envelope: TypedEnvelope<proto::OpenBufferByPath>,
4593 mut cx: AsyncApp,
4594 ) -> Result<proto::OpenBufferResponse> {
4595 let peer_id = envelope.original_sender_id()?;
4596 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4597 let open_buffer = this.update(&mut cx, |this, cx| {
4598 this.open_buffer(
4599 ProjectPath {
4600 worktree_id,
4601 path: Arc::<Path>::from_proto(envelope.payload.path),
4602 },
4603 cx,
4604 )
4605 })?;
4606
4607 let buffer = open_buffer.await?;
4608 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4609 }
4610
4611 async fn handle_open_new_buffer(
4612 this: Entity<Self>,
4613 envelope: TypedEnvelope<proto::OpenNewBuffer>,
4614 mut cx: AsyncApp,
4615 ) -> Result<proto::OpenBufferResponse> {
4616 let buffer = this
4617 .update(&mut cx, |this, cx| this.create_buffer(cx))?
4618 .await?;
4619 let peer_id = envelope.original_sender_id()?;
4620
4621 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4622 }
4623
4624 fn respond_to_open_buffer_request(
4625 this: Entity<Self>,
4626 buffer: Entity<Buffer>,
4627 peer_id: proto::PeerId,
4628 cx: &mut AsyncApp,
4629 ) -> Result<proto::OpenBufferResponse> {
4630 this.update(cx, |this, cx| {
4631 let is_private = buffer
4632 .read(cx)
4633 .file()
4634 .map(|f| f.is_private())
4635 .unwrap_or_default();
4636 if is_private {
4637 Err(anyhow!(ErrorCode::UnsharedItem))
4638 } else {
4639 Ok(proto::OpenBufferResponse {
4640 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4641 })
4642 }
4643 })?
4644 }
4645
4646 fn create_buffer_for_peer(
4647 &mut self,
4648 buffer: &Entity<Buffer>,
4649 peer_id: proto::PeerId,
4650 cx: &mut App,
4651 ) -> BufferId {
4652 self.buffer_store
4653 .update(cx, |buffer_store, cx| {
4654 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4655 })
4656 .detach_and_log_err(cx);
4657 buffer.read(cx).remote_id()
4658 }
4659
4660 fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4661 let project_id = match self.client_state {
4662 ProjectClientState::Remote {
4663 sharing_has_stopped,
4664 remote_id,
4665 ..
4666 } => {
4667 if sharing_has_stopped {
4668 return Task::ready(Err(anyhow!(
4669 "can't synchronize remote buffers on a readonly project"
4670 )));
4671 } else {
4672 remote_id
4673 }
4674 }
4675 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4676 return Task::ready(Err(anyhow!(
4677 "can't synchronize remote buffers on a local project"
4678 )));
4679 }
4680 };
4681
4682 let client = self.client.clone();
4683 cx.spawn(async move |this, cx| {
4684 let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
4685 this.buffer_store.read(cx).buffer_version_info(cx)
4686 })?;
4687 let response = client
4688 .request(proto::SynchronizeBuffers {
4689 project_id,
4690 buffers,
4691 })
4692 .await?;
4693
4694 let send_updates_for_buffers = this.update(cx, |this, cx| {
4695 response
4696 .buffers
4697 .into_iter()
4698 .map(|buffer| {
4699 let client = client.clone();
4700 let buffer_id = match BufferId::new(buffer.id) {
4701 Ok(id) => id,
4702 Err(e) => {
4703 return Task::ready(Err(e));
4704 }
4705 };
4706 let remote_version = language::proto::deserialize_version(&buffer.version);
4707 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4708 let operations =
4709 buffer.read(cx).serialize_ops(Some(remote_version), cx);
4710 cx.background_spawn(async move {
4711 let operations = operations.await;
4712 for chunk in split_operations(operations) {
4713 client
4714 .request(proto::UpdateBuffer {
4715 project_id,
4716 buffer_id: buffer_id.into(),
4717 operations: chunk,
4718 })
4719 .await?;
4720 }
4721 anyhow::Ok(())
4722 })
4723 } else {
4724 Task::ready(Ok(()))
4725 }
4726 })
4727 .collect::<Vec<_>>()
4728 })?;
4729
4730 // Any incomplete buffers have open requests waiting. Request that the host sends
4731 // creates these buffers for us again to unblock any waiting futures.
4732 for id in incomplete_buffer_ids {
4733 cx.background_spawn(client.request(proto::OpenBufferById {
4734 project_id,
4735 id: id.into(),
4736 }))
4737 .detach();
4738 }
4739
4740 futures::future::join_all(send_updates_for_buffers)
4741 .await
4742 .into_iter()
4743 .collect()
4744 })
4745 }
4746
4747 pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4748 self.worktree_store.read(cx).worktree_metadata_protos(cx)
4749 }
4750
4751 /// Iterator of all open buffers that have unsaved changes
4752 pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4753 self.buffer_store.read(cx).buffers().filter_map(|buf| {
4754 let buf = buf.read(cx);
4755 if buf.is_dirty() {
4756 buf.project_path(cx)
4757 } else {
4758 None
4759 }
4760 })
4761 }
4762
4763 fn set_worktrees_from_proto(
4764 &mut self,
4765 worktrees: Vec<proto::WorktreeMetadata>,
4766 cx: &mut Context<Project>,
4767 ) -> Result<()> {
4768 self.worktree_store.update(cx, |worktree_store, cx| {
4769 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4770 })
4771 }
4772
4773 fn set_collaborators_from_proto(
4774 &mut self,
4775 messages: Vec<proto::Collaborator>,
4776 cx: &mut Context<Self>,
4777 ) -> Result<()> {
4778 let mut collaborators = HashMap::default();
4779 for message in messages {
4780 let collaborator = Collaborator::from_proto(message)?;
4781 collaborators.insert(collaborator.peer_id, collaborator);
4782 }
4783 for old_peer_id in self.collaborators.keys() {
4784 if !collaborators.contains_key(old_peer_id) {
4785 cx.emit(Event::CollaboratorLeft(*old_peer_id));
4786 }
4787 }
4788 self.collaborators = collaborators;
4789 Ok(())
4790 }
4791
4792 pub fn supplementary_language_servers<'a>(
4793 &'a self,
4794 cx: &'a App,
4795 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4796 self.lsp_store.read(cx).supplementary_language_servers()
4797 }
4798
4799 pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
4800 self.lsp_store.update(cx, |this, cx| {
4801 this.language_servers_for_local_buffer(buffer, cx)
4802 .any(
4803 |(_, server)| match server.capabilities().inlay_hint_provider {
4804 Some(lsp::OneOf::Left(enabled)) => enabled,
4805 Some(lsp::OneOf::Right(_)) => true,
4806 None => false,
4807 },
4808 )
4809 })
4810 }
4811
4812 pub fn language_server_id_for_name(
4813 &self,
4814 buffer: &Buffer,
4815 name: &str,
4816 cx: &mut App,
4817 ) -> Task<Option<LanguageServerId>> {
4818 if self.is_local() {
4819 Task::ready(self.lsp_store.update(cx, |lsp_store, cx| {
4820 lsp_store
4821 .language_servers_for_local_buffer(buffer, cx)
4822 .find_map(|(adapter, server)| {
4823 if adapter.name.0 == name {
4824 Some(server.server_id())
4825 } else {
4826 None
4827 }
4828 })
4829 }))
4830 } else if let Some(project_id) = self.remote_id() {
4831 let request = self.client.request(proto::LanguageServerIdForName {
4832 project_id,
4833 buffer_id: buffer.remote_id().to_proto(),
4834 name: name.to_string(),
4835 });
4836 cx.background_spawn(async move {
4837 let response = request.await.log_err()?;
4838 response.server_id.map(LanguageServerId::from_proto)
4839 })
4840 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
4841 let request =
4842 ssh_client
4843 .read(cx)
4844 .proto_client()
4845 .request(proto::LanguageServerIdForName {
4846 project_id: SSH_PROJECT_ID,
4847 buffer_id: buffer.remote_id().to_proto(),
4848 name: name.to_string(),
4849 });
4850 cx.background_spawn(async move {
4851 let response = request.await.log_err()?;
4852 response.server_id.map(LanguageServerId::from_proto)
4853 })
4854 } else {
4855 Task::ready(None)
4856 }
4857 }
4858
4859 pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
4860 self.lsp_store.update(cx, |this, cx| {
4861 this.language_servers_for_local_buffer(buffer, cx)
4862 .next()
4863 .is_some()
4864 })
4865 }
4866
4867 pub fn git_init(
4868 &self,
4869 path: Arc<Path>,
4870 fallback_branch_name: String,
4871 cx: &App,
4872 ) -> Task<Result<()>> {
4873 self.git_store
4874 .read(cx)
4875 .git_init(path, fallback_branch_name, cx)
4876 }
4877
4878 pub fn buffer_store(&self) -> &Entity<BufferStore> {
4879 &self.buffer_store
4880 }
4881
4882 pub fn git_store(&self) -> &Entity<GitStore> {
4883 &self.git_store
4884 }
4885
4886 #[cfg(test)]
4887 fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
4888 cx.spawn(async move |this, cx| {
4889 let scans_complete = this
4890 .read_with(cx, |this, cx| {
4891 this.worktrees(cx)
4892 .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
4893 .collect::<Vec<_>>()
4894 })
4895 .unwrap();
4896 join_all(scans_complete).await;
4897 let barriers = this
4898 .update(cx, |this, cx| {
4899 let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
4900 repos
4901 .into_iter()
4902 .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
4903 .collect::<Vec<_>>()
4904 })
4905 .unwrap();
4906 join_all(barriers).await;
4907 })
4908 }
4909
4910 pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
4911 self.git_store.read(cx).active_repository()
4912 }
4913
4914 pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
4915 self.git_store.read(cx).repositories()
4916 }
4917
4918 pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
4919 self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
4920 }
4921
4922 pub fn set_agent_location(
4923 &mut self,
4924 new_location: Option<AgentLocation>,
4925 cx: &mut Context<Self>,
4926 ) {
4927 if let Some(old_location) = self.agent_location.as_ref() {
4928 old_location
4929 .buffer
4930 .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
4931 .ok();
4932 }
4933
4934 if let Some(location) = new_location.as_ref() {
4935 location
4936 .buffer
4937 .update(cx, |buffer, cx| {
4938 buffer.set_agent_selections(
4939 Arc::from([language::Selection {
4940 id: 0,
4941 start: location.position,
4942 end: location.position,
4943 reversed: false,
4944 goal: language::SelectionGoal::None,
4945 }]),
4946 false,
4947 CursorShape::Hollow,
4948 cx,
4949 )
4950 })
4951 .ok();
4952 }
4953
4954 self.agent_location = new_location;
4955 cx.emit(Event::AgentLocationChanged);
4956 }
4957
4958 pub fn agent_location(&self) -> Option<AgentLocation> {
4959 self.agent_location.clone()
4960 }
4961}
4962
4963pub struct PathMatchCandidateSet {
4964 pub snapshot: Snapshot,
4965 pub include_ignored: bool,
4966 pub include_root_name: bool,
4967 pub candidates: Candidates,
4968}
4969
4970pub enum Candidates {
4971 /// Only consider directories.
4972 Directories,
4973 /// Only consider files.
4974 Files,
4975 /// Consider directories and files.
4976 Entries,
4977}
4978
4979impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4980 type Candidates = PathMatchCandidateSetIter<'a>;
4981
4982 fn id(&self) -> usize {
4983 self.snapshot.id().to_usize()
4984 }
4985
4986 fn len(&self) -> usize {
4987 match self.candidates {
4988 Candidates::Files => {
4989 if self.include_ignored {
4990 self.snapshot.file_count()
4991 } else {
4992 self.snapshot.visible_file_count()
4993 }
4994 }
4995
4996 Candidates::Directories => {
4997 if self.include_ignored {
4998 self.snapshot.dir_count()
4999 } else {
5000 self.snapshot.visible_dir_count()
5001 }
5002 }
5003
5004 Candidates::Entries => {
5005 if self.include_ignored {
5006 self.snapshot.entry_count()
5007 } else {
5008 self.snapshot.visible_entry_count()
5009 }
5010 }
5011 }
5012 }
5013
5014 fn prefix(&self) -> Arc<str> {
5015 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5016 self.snapshot.root_name().into()
5017 } else if self.include_root_name {
5018 format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
5019 } else {
5020 Arc::default()
5021 }
5022 }
5023
5024 fn candidates(&'a self, start: usize) -> Self::Candidates {
5025 PathMatchCandidateSetIter {
5026 traversal: match self.candidates {
5027 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5028 Candidates::Files => self.snapshot.files(self.include_ignored, start),
5029 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5030 },
5031 }
5032 }
5033}
5034
5035pub struct PathMatchCandidateSetIter<'a> {
5036 traversal: Traversal<'a>,
5037}
5038
5039impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5040 type Item = fuzzy::PathMatchCandidate<'a>;
5041
5042 fn next(&mut self) -> Option<Self::Item> {
5043 self.traversal
5044 .next()
5045 .map(|entry| fuzzy::PathMatchCandidate {
5046 is_dir: entry.kind.is_dir(),
5047 path: &entry.path,
5048 char_bag: entry.char_bag,
5049 })
5050 }
5051}
5052
5053impl EventEmitter<Event> for Project {}
5054
5055impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5056 fn from(val: &'a ProjectPath) -> Self {
5057 SettingsLocation {
5058 worktree_id: val.worktree_id,
5059 path: val.path.as_ref(),
5060 }
5061 }
5062}
5063
5064impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
5065 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5066 Self {
5067 worktree_id,
5068 path: path.as_ref().into(),
5069 }
5070 }
5071}
5072
5073pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
5074 let mut path_components = path.components();
5075 let mut base_components = base.components();
5076 let mut components: Vec<Component> = Vec::new();
5077 loop {
5078 match (path_components.next(), base_components.next()) {
5079 (None, None) => break,
5080 (Some(a), None) => {
5081 components.push(a);
5082 components.extend(path_components.by_ref());
5083 break;
5084 }
5085 (None, _) => components.push(Component::ParentDir),
5086 (Some(a), Some(b)) if components.is_empty() && a == b => (),
5087 (Some(a), Some(Component::CurDir)) => components.push(a),
5088 (Some(a), Some(_)) => {
5089 components.push(Component::ParentDir);
5090 for _ in base_components {
5091 components.push(Component::ParentDir);
5092 }
5093 components.push(a);
5094 components.extend(path_components.by_ref());
5095 break;
5096 }
5097 }
5098 }
5099 components.iter().map(|c| c.as_os_str()).collect()
5100}
5101
5102fn resolve_path(base: &Path, path: &Path) -> PathBuf {
5103 let mut result = base.to_path_buf();
5104 for component in path.components() {
5105 match component {
5106 Component::ParentDir => {
5107 result.pop();
5108 }
5109 Component::CurDir => (),
5110 _ => result.push(component),
5111 }
5112 }
5113 result
5114}
5115
5116/// ResolvedPath is a path that has been resolved to either a ProjectPath
5117/// or an AbsPath and that *exists*.
5118#[derive(Debug, Clone)]
5119pub enum ResolvedPath {
5120 ProjectPath {
5121 project_path: ProjectPath,
5122 is_dir: bool,
5123 },
5124 AbsPath {
5125 path: PathBuf,
5126 is_dir: bool,
5127 },
5128}
5129
5130impl ResolvedPath {
5131 pub fn abs_path(&self) -> Option<&Path> {
5132 match self {
5133 Self::AbsPath { path, .. } => Some(path.as_path()),
5134 _ => None,
5135 }
5136 }
5137
5138 pub fn into_abs_path(self) -> Option<PathBuf> {
5139 match self {
5140 Self::AbsPath { path, .. } => Some(path),
5141 _ => None,
5142 }
5143 }
5144
5145 pub fn project_path(&self) -> Option<&ProjectPath> {
5146 match self {
5147 Self::ProjectPath { project_path, .. } => Some(&project_path),
5148 _ => None,
5149 }
5150 }
5151
5152 pub fn is_file(&self) -> bool {
5153 !self.is_dir()
5154 }
5155
5156 pub fn is_dir(&self) -> bool {
5157 match self {
5158 Self::ProjectPath { is_dir, .. } => *is_dir,
5159 Self::AbsPath { is_dir, .. } => *is_dir,
5160 }
5161 }
5162}
5163
5164impl ProjectItem for Buffer {
5165 fn try_open(
5166 project: &Entity<Project>,
5167 path: &ProjectPath,
5168 cx: &mut App,
5169 ) -> Option<Task<Result<Entity<Self>>>> {
5170 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5171 }
5172
5173 fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
5174 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
5175 }
5176
5177 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5178 self.file().map(|file| ProjectPath {
5179 worktree_id: file.worktree_id(cx),
5180 path: file.path().clone(),
5181 })
5182 }
5183
5184 fn is_dirty(&self) -> bool {
5185 self.is_dirty()
5186 }
5187}
5188
5189impl Completion {
5190 pub fn kind(&self) -> Option<CompletionItemKind> {
5191 self.source
5192 // `lsp::CompletionListItemDefaults` has no `kind` field
5193 .lsp_completion(false)
5194 .and_then(|lsp_completion| lsp_completion.kind)
5195 }
5196
5197 pub fn label(&self) -> Option<String> {
5198 self.source
5199 .lsp_completion(false)
5200 .map(|lsp_completion| lsp_completion.label.clone())
5201 }
5202
5203 /// A key that can be used to sort completions when displaying
5204 /// them to the user.
5205 pub fn sort_key(&self) -> (usize, &str) {
5206 const DEFAULT_KIND_KEY: usize = 3;
5207 let kind_key = self
5208 .kind()
5209 .and_then(|lsp_completion_kind| match lsp_completion_kind {
5210 lsp::CompletionItemKind::KEYWORD => Some(0),
5211 lsp::CompletionItemKind::VARIABLE => Some(1),
5212 lsp::CompletionItemKind::CONSTANT => Some(2),
5213 _ => None,
5214 })
5215 .unwrap_or(DEFAULT_KIND_KEY);
5216 (kind_key, &self.label.text[self.label.filter_range.clone()])
5217 }
5218
5219 /// Whether this completion is a snippet.
5220 pub fn is_snippet(&self) -> bool {
5221 self.source
5222 // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5223 .lsp_completion(true)
5224 .map_or(false, |lsp_completion| {
5225 lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5226 })
5227 }
5228
5229 /// Returns the corresponding color for this completion.
5230 ///
5231 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5232 pub fn color(&self) -> Option<Hsla> {
5233 // `lsp::CompletionListItemDefaults` has no `kind` field
5234 let lsp_completion = self.source.lsp_completion(false)?;
5235 if lsp_completion.kind? == CompletionItemKind::COLOR {
5236 return color_extractor::extract_color(&lsp_completion);
5237 }
5238 None
5239 }
5240}
5241
5242pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
5243 entries.sort_by(|entry_a, entry_b| {
5244 let entry_a = entry_a.as_ref();
5245 let entry_b = entry_b.as_ref();
5246 compare_paths(
5247 (&entry_a.path, entry_a.is_file()),
5248 (&entry_b.path, entry_b.is_file()),
5249 )
5250 });
5251}
5252
5253fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5254 match level {
5255 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5256 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5257 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5258 }
5259}