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