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