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