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.update(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.update(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.update(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 .update(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.update(cx, |this, _| {
2554 let project_id = this.remote_id()?;
2555 Some(this.client.request(proto::UpdateBuffer {
2556 buffer_id: buffer_id.into(),
2557 project_id,
2558 operations,
2559 }))
2560 })?;
2561 if let Some(request) = request {
2562 if request.await.is_err() && !is_local {
2563 *needs_resync_with_host = true;
2564 break;
2565 }
2566 }
2567 }
2568 Ok(())
2569 }
2570
2571 let mut needs_resync_with_host = false;
2572 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2573
2574 while let Some(changes) = changes.next().await {
2575 let is_local = this.update(cx, |this, _| this.is_local())?;
2576
2577 for change in changes {
2578 match change {
2579 BufferOrderedMessage::Operation {
2580 buffer_id,
2581 operation,
2582 } => {
2583 if needs_resync_with_host {
2584 continue;
2585 }
2586
2587 operations_by_buffer_id
2588 .entry(buffer_id)
2589 .or_insert(Vec::new())
2590 .push(operation);
2591 }
2592
2593 BufferOrderedMessage::Resync => {
2594 operations_by_buffer_id.clear();
2595 if this
2596 .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
2597 .await
2598 .is_ok()
2599 {
2600 needs_resync_with_host = false;
2601 }
2602 }
2603
2604 BufferOrderedMessage::LanguageServerUpdate {
2605 language_server_id,
2606 message,
2607 } => {
2608 flush_operations(
2609 &this,
2610 &mut operations_by_buffer_id,
2611 &mut needs_resync_with_host,
2612 is_local,
2613 cx,
2614 )
2615 .await?;
2616
2617 this.update(cx, |this, _| {
2618 if let Some(project_id) = this.remote_id() {
2619 this.client
2620 .send(proto::UpdateLanguageServer {
2621 project_id,
2622 language_server_id: language_server_id.0 as u64,
2623 variant: Some(message),
2624 })
2625 .log_err();
2626 }
2627 })?;
2628 }
2629 }
2630 }
2631
2632 flush_operations(
2633 &this,
2634 &mut operations_by_buffer_id,
2635 &mut needs_resync_with_host,
2636 is_local,
2637 cx,
2638 )
2639 .await?;
2640 }
2641
2642 Ok(())
2643 }
2644
2645 fn on_buffer_store_event(
2646 &mut self,
2647 _: Entity<BufferStore>,
2648 event: &BufferStoreEvent,
2649 cx: &mut Context<Self>,
2650 ) {
2651 match event {
2652 BufferStoreEvent::BufferAdded(buffer) => {
2653 self.register_buffer(buffer, cx).log_err();
2654 }
2655 BufferStoreEvent::BufferDropped(buffer_id) => {
2656 if let Some(ref ssh_client) = self.ssh_client {
2657 ssh_client
2658 .read(cx)
2659 .proto_client()
2660 .send(proto::CloseBuffer {
2661 project_id: 0,
2662 buffer_id: buffer_id.to_proto(),
2663 })
2664 .log_err();
2665 }
2666 }
2667 _ => {}
2668 }
2669 }
2670
2671 fn on_image_store_event(
2672 &mut self,
2673 _: Entity<ImageStore>,
2674 event: &ImageStoreEvent,
2675 cx: &mut Context<Self>,
2676 ) {
2677 match event {
2678 ImageStoreEvent::ImageAdded(image) => {
2679 cx.subscribe(image, |this, image, event, cx| {
2680 this.on_image_event(image, event, cx);
2681 })
2682 .detach();
2683 }
2684 }
2685 }
2686
2687 fn on_dap_store_event(
2688 &mut self,
2689 _: Entity<DapStore>,
2690 event: &DapStoreEvent,
2691 cx: &mut Context<Self>,
2692 ) {
2693 match event {
2694 DapStoreEvent::Notification(message) => {
2695 cx.emit(Event::Toast {
2696 notification_id: "dap".into(),
2697 message: message.clone(),
2698 });
2699 }
2700 _ => {}
2701 }
2702 }
2703
2704 fn on_lsp_store_event(
2705 &mut self,
2706 _: Entity<LspStore>,
2707 event: &LspStoreEvent,
2708 cx: &mut Context<Self>,
2709 ) {
2710 match event {
2711 LspStoreEvent::DiagnosticsUpdated {
2712 language_server_id,
2713 path,
2714 } => cx.emit(Event::DiagnosticsUpdated {
2715 path: path.clone(),
2716 language_server_id: *language_server_id,
2717 }),
2718 LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2719 Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2720 ),
2721 LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2722 cx.emit(Event::LanguageServerRemoved(*language_server_id))
2723 }
2724 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2725 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2726 ),
2727 LspStoreEvent::LanguageDetected {
2728 buffer,
2729 new_language,
2730 } => {
2731 let Some(_) = new_language else {
2732 cx.emit(Event::LanguageNotFound(buffer.clone()));
2733 return;
2734 };
2735 }
2736 LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2737 LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
2738 LspStoreEvent::LanguageServerPrompt(prompt) => {
2739 cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2740 }
2741 LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2742 cx.emit(Event::DiskBasedDiagnosticsStarted {
2743 language_server_id: *language_server_id,
2744 });
2745 }
2746 LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2747 cx.emit(Event::DiskBasedDiagnosticsFinished {
2748 language_server_id: *language_server_id,
2749 });
2750 }
2751 LspStoreEvent::LanguageServerUpdate {
2752 language_server_id,
2753 message,
2754 } => {
2755 if self.is_local() {
2756 self.enqueue_buffer_ordered_message(
2757 BufferOrderedMessage::LanguageServerUpdate {
2758 language_server_id: *language_server_id,
2759 message: message.clone(),
2760 },
2761 )
2762 .ok();
2763 }
2764 }
2765 LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2766 notification_id: "lsp".into(),
2767 message: message.clone(),
2768 }),
2769 LspStoreEvent::SnippetEdit {
2770 buffer_id,
2771 edits,
2772 most_recent_edit,
2773 } => {
2774 if most_recent_edit.replica_id == self.replica_id() {
2775 cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2776 }
2777 }
2778 }
2779 }
2780
2781 fn on_ssh_event(
2782 &mut self,
2783 _: Entity<SshRemoteClient>,
2784 event: &remote::SshRemoteEvent,
2785 cx: &mut Context<Self>,
2786 ) {
2787 match event {
2788 remote::SshRemoteEvent::Disconnected => {
2789 // if self.is_via_ssh() {
2790 // self.collaborators.clear();
2791 self.worktree_store.update(cx, |store, cx| {
2792 store.disconnected_from_host(cx);
2793 });
2794 self.buffer_store.update(cx, |buffer_store, cx| {
2795 buffer_store.disconnected_from_host(cx)
2796 });
2797 self.lsp_store.update(cx, |lsp_store, _cx| {
2798 lsp_store.disconnected_from_ssh_remote()
2799 });
2800 cx.emit(Event::DisconnectedFromSshRemote);
2801 }
2802 }
2803 }
2804
2805 fn on_settings_observer_event(
2806 &mut self,
2807 _: Entity<SettingsObserver>,
2808 event: &SettingsObserverEvent,
2809 cx: &mut Context<Self>,
2810 ) {
2811 match event {
2812 SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2813 Err(InvalidSettingsError::LocalSettings { message, path }) => {
2814 let message = format!("Failed to set local settings in {path:?}:\n{message}");
2815 cx.emit(Event::Toast {
2816 notification_id: format!("local-settings-{path:?}").into(),
2817 message,
2818 });
2819 }
2820 Ok(path) => cx.emit(Event::HideToast {
2821 notification_id: format!("local-settings-{path:?}").into(),
2822 }),
2823 Err(_) => {}
2824 },
2825 SettingsObserverEvent::LocalTasksUpdated(result) => match result {
2826 Err(InvalidSettingsError::Tasks { message, path }) => {
2827 let message = format!("Failed to set local tasks in {path:?}:\n{message}");
2828 cx.emit(Event::Toast {
2829 notification_id: format!("local-tasks-{path:?}").into(),
2830 message,
2831 });
2832 }
2833 Ok(path) => cx.emit(Event::HideToast {
2834 notification_id: format!("local-tasks-{path:?}").into(),
2835 }),
2836 Err(_) => {}
2837 },
2838 }
2839 }
2840
2841 fn on_worktree_store_event(
2842 &mut self,
2843 _: Entity<WorktreeStore>,
2844 event: &WorktreeStoreEvent,
2845 cx: &mut Context<Self>,
2846 ) {
2847 match event {
2848 WorktreeStoreEvent::WorktreeAdded(worktree) => {
2849 self.on_worktree_added(worktree, cx);
2850 cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
2851 }
2852 WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2853 cx.emit(Event::WorktreeRemoved(*id));
2854 }
2855 WorktreeStoreEvent::WorktreeReleased(_, id) => {
2856 self.on_worktree_released(*id, cx);
2857 }
2858 WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2859 WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2860 WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
2861 self.client()
2862 .telemetry()
2863 .report_discovered_project_events(*worktree_id, changes);
2864 cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
2865 }
2866 WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
2867 cx.emit(Event::DeletedEntry(*worktree_id, *id))
2868 }
2869 // Listen to the GitStore instead.
2870 WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
2871 }
2872 }
2873
2874 fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
2875 let mut remotely_created_models = self.remotely_created_models.lock();
2876 if remotely_created_models.retain_count > 0 {
2877 remotely_created_models.worktrees.push(worktree.clone())
2878 }
2879 }
2880
2881 fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
2882 if let Some(ssh) = &self.ssh_client {
2883 ssh.read(cx)
2884 .proto_client()
2885 .send(proto::RemoveWorktree {
2886 worktree_id: id_to_remove.to_proto(),
2887 })
2888 .log_err();
2889 }
2890 }
2891
2892 fn on_buffer_event(
2893 &mut self,
2894 buffer: Entity<Buffer>,
2895 event: &BufferEvent,
2896 cx: &mut Context<Self>,
2897 ) -> Option<()> {
2898 if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
2899 self.request_buffer_diff_recalculation(&buffer, cx);
2900 }
2901
2902 let buffer_id = buffer.read(cx).remote_id();
2903 match event {
2904 BufferEvent::ReloadNeeded => {
2905 if !self.is_via_collab() {
2906 self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
2907 .detach_and_log_err(cx);
2908 }
2909 }
2910 BufferEvent::Operation {
2911 operation,
2912 is_local: true,
2913 } => {
2914 let operation = language::proto::serialize_operation(operation);
2915
2916 if let Some(ssh) = &self.ssh_client {
2917 ssh.read(cx)
2918 .proto_client()
2919 .send(proto::UpdateBuffer {
2920 project_id: 0,
2921 buffer_id: buffer_id.to_proto(),
2922 operations: vec![operation.clone()],
2923 })
2924 .ok();
2925 }
2926
2927 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2928 buffer_id,
2929 operation,
2930 })
2931 .ok();
2932 }
2933
2934 _ => {}
2935 }
2936
2937 None
2938 }
2939
2940 fn on_image_event(
2941 &mut self,
2942 image: Entity<ImageItem>,
2943 event: &ImageItemEvent,
2944 cx: &mut Context<Self>,
2945 ) -> Option<()> {
2946 match event {
2947 ImageItemEvent::ReloadNeeded => {
2948 if !self.is_via_collab() {
2949 self.reload_images([image.clone()].into_iter().collect(), cx)
2950 .detach_and_log_err(cx);
2951 }
2952 }
2953 _ => {}
2954 }
2955
2956 None
2957 }
2958
2959 fn request_buffer_diff_recalculation(
2960 &mut self,
2961 buffer: &Entity<Buffer>,
2962 cx: &mut Context<Self>,
2963 ) {
2964 self.buffers_needing_diff.insert(buffer.downgrade());
2965 let first_insertion = self.buffers_needing_diff.len() == 1;
2966
2967 let settings = ProjectSettings::get_global(cx);
2968 let delay = if let Some(delay) = settings.git.gutter_debounce {
2969 delay
2970 } else {
2971 if first_insertion {
2972 let this = cx.weak_entity();
2973 cx.defer(move |cx| {
2974 if let Some(this) = this.upgrade() {
2975 this.update(cx, |this, cx| {
2976 this.recalculate_buffer_diffs(cx).detach();
2977 });
2978 }
2979 });
2980 }
2981 return;
2982 };
2983
2984 const MIN_DELAY: u64 = 50;
2985 let delay = delay.max(MIN_DELAY);
2986 let duration = Duration::from_millis(delay);
2987
2988 self.git_diff_debouncer
2989 .fire_new(duration, cx, move |this, cx| {
2990 this.recalculate_buffer_diffs(cx)
2991 });
2992 }
2993
2994 fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
2995 cx.spawn(async move |this, cx| {
2996 loop {
2997 let task = this
2998 .update(cx, |this, cx| {
2999 let buffers = this
3000 .buffers_needing_diff
3001 .drain()
3002 .filter_map(|buffer| buffer.upgrade())
3003 .collect::<Vec<_>>();
3004 if buffers.is_empty() {
3005 None
3006 } else {
3007 Some(this.git_store.update(cx, |git_store, cx| {
3008 git_store.recalculate_buffer_diffs(buffers, cx)
3009 }))
3010 }
3011 })
3012 .ok()
3013 .flatten();
3014
3015 if let Some(task) = task {
3016 task.await;
3017 } else {
3018 break;
3019 }
3020 }
3021 })
3022 }
3023
3024 pub fn set_language_for_buffer(
3025 &mut self,
3026 buffer: &Entity<Buffer>,
3027 new_language: Arc<Language>,
3028 cx: &mut Context<Self>,
3029 ) {
3030 self.lsp_store.update(cx, |lsp_store, cx| {
3031 lsp_store.set_language_for_buffer(buffer, new_language, cx)
3032 })
3033 }
3034
3035 pub fn restart_language_servers_for_buffers(
3036 &mut self,
3037 buffers: Vec<Entity<Buffer>>,
3038 cx: &mut Context<Self>,
3039 ) {
3040 self.lsp_store.update(cx, |lsp_store, cx| {
3041 lsp_store.restart_language_servers_for_buffers(buffers, cx)
3042 })
3043 }
3044
3045 pub fn stop_language_servers_for_buffers(
3046 &mut self,
3047 buffers: Vec<Entity<Buffer>>,
3048 cx: &mut Context<Self>,
3049 ) {
3050 self.lsp_store.update(cx, |lsp_store, cx| {
3051 lsp_store.stop_language_servers_for_buffers(buffers, cx)
3052 })
3053 }
3054
3055 pub fn cancel_language_server_work_for_buffers(
3056 &mut self,
3057 buffers: impl IntoIterator<Item = Entity<Buffer>>,
3058 cx: &mut Context<Self>,
3059 ) {
3060 self.lsp_store.update(cx, |lsp_store, cx| {
3061 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
3062 })
3063 }
3064
3065 pub fn cancel_language_server_work(
3066 &mut self,
3067 server_id: LanguageServerId,
3068 token_to_cancel: Option<String>,
3069 cx: &mut Context<Self>,
3070 ) {
3071 self.lsp_store.update(cx, |lsp_store, cx| {
3072 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
3073 })
3074 }
3075
3076 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3077 self.buffer_ordered_messages_tx
3078 .unbounded_send(message)
3079 .map_err(|e| anyhow!(e))
3080 }
3081
3082 pub fn available_toolchains(
3083 &self,
3084 path: ProjectPath,
3085 language_name: LanguageName,
3086 cx: &App,
3087 ) -> Task<Option<ToolchainList>> {
3088 if let Some(toolchain_store) = self.toolchain_store.clone() {
3089 cx.spawn(async move |cx| {
3090 cx.update(|cx| {
3091 toolchain_store
3092 .read(cx)
3093 .list_toolchains(path, language_name, cx)
3094 })
3095 .ok()?
3096 .await
3097 })
3098 } else {
3099 Task::ready(None)
3100 }
3101 }
3102
3103 pub async fn toolchain_term(
3104 languages: Arc<LanguageRegistry>,
3105 language_name: LanguageName,
3106 ) -> Option<SharedString> {
3107 languages
3108 .language_for_name(language_name.as_ref())
3109 .await
3110 .ok()?
3111 .toolchain_lister()
3112 .map(|lister| lister.term())
3113 }
3114
3115 pub fn toolchain_store(&self) -> Option<Entity<ToolchainStore>> {
3116 self.toolchain_store.clone()
3117 }
3118 pub fn activate_toolchain(
3119 &self,
3120 path: ProjectPath,
3121 toolchain: Toolchain,
3122 cx: &mut App,
3123 ) -> Task<Option<()>> {
3124 let Some(toolchain_store) = self.toolchain_store.clone() else {
3125 return Task::ready(None);
3126 };
3127 toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
3128 }
3129 pub fn active_toolchain(
3130 &self,
3131 path: ProjectPath,
3132 language_name: LanguageName,
3133 cx: &App,
3134 ) -> Task<Option<Toolchain>> {
3135 let Some(toolchain_store) = self.toolchain_store.clone() else {
3136 return Task::ready(None);
3137 };
3138 toolchain_store
3139 .read(cx)
3140 .active_toolchain(path, language_name, cx)
3141 }
3142 pub fn language_server_statuses<'a>(
3143 &'a self,
3144 cx: &'a App,
3145 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
3146 self.lsp_store.read(cx).language_server_statuses()
3147 }
3148
3149 pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
3150 self.lsp_store.read(cx).last_formatting_failure()
3151 }
3152
3153 pub fn reset_last_formatting_failure(&self, cx: &mut App) {
3154 self.lsp_store
3155 .update(cx, |store, _| store.reset_last_formatting_failure());
3156 }
3157
3158 pub fn reload_buffers(
3159 &self,
3160 buffers: HashSet<Entity<Buffer>>,
3161 push_to_history: bool,
3162 cx: &mut Context<Self>,
3163 ) -> Task<Result<ProjectTransaction>> {
3164 self.buffer_store.update(cx, |buffer_store, cx| {
3165 buffer_store.reload_buffers(buffers, push_to_history, cx)
3166 })
3167 }
3168
3169 pub fn reload_images(
3170 &self,
3171 images: HashSet<Entity<ImageItem>>,
3172 cx: &mut Context<Self>,
3173 ) -> Task<Result<()>> {
3174 self.image_store
3175 .update(cx, |image_store, cx| image_store.reload_images(images, cx))
3176 }
3177
3178 pub fn format(
3179 &mut self,
3180 buffers: HashSet<Entity<Buffer>>,
3181 target: LspFormatTarget,
3182 push_to_history: bool,
3183 trigger: lsp_store::FormatTrigger,
3184 cx: &mut Context<Project>,
3185 ) -> Task<anyhow::Result<ProjectTransaction>> {
3186 self.lsp_store.update(cx, |lsp_store, cx| {
3187 lsp_store.format(buffers, target, push_to_history, trigger, cx)
3188 })
3189 }
3190
3191 #[inline(never)]
3192 fn definition_impl(
3193 &mut self,
3194 buffer: &Entity<Buffer>,
3195 position: PointUtf16,
3196 cx: &mut Context<Self>,
3197 ) -> Task<Result<Vec<LocationLink>>> {
3198 self.request_lsp(
3199 buffer.clone(),
3200 LanguageServerToQuery::FirstCapable,
3201 GetDefinition { position },
3202 cx,
3203 )
3204 }
3205 pub fn definition<T: ToPointUtf16>(
3206 &mut self,
3207 buffer: &Entity<Buffer>,
3208 position: T,
3209 cx: &mut Context<Self>,
3210 ) -> Task<Result<Vec<LocationLink>>> {
3211 let position = position.to_point_utf16(buffer.read(cx));
3212 self.definition_impl(buffer, position, cx)
3213 }
3214
3215 fn declaration_impl(
3216 &mut self,
3217 buffer: &Entity<Buffer>,
3218 position: PointUtf16,
3219 cx: &mut Context<Self>,
3220 ) -> Task<Result<Vec<LocationLink>>> {
3221 self.request_lsp(
3222 buffer.clone(),
3223 LanguageServerToQuery::FirstCapable,
3224 GetDeclaration { position },
3225 cx,
3226 )
3227 }
3228
3229 pub fn declaration<T: ToPointUtf16>(
3230 &mut self,
3231 buffer: &Entity<Buffer>,
3232 position: T,
3233 cx: &mut Context<Self>,
3234 ) -> Task<Result<Vec<LocationLink>>> {
3235 let position = position.to_point_utf16(buffer.read(cx));
3236 self.declaration_impl(buffer, position, cx)
3237 }
3238
3239 fn type_definition_impl(
3240 &mut self,
3241 buffer: &Entity<Buffer>,
3242 position: PointUtf16,
3243 cx: &mut Context<Self>,
3244 ) -> Task<Result<Vec<LocationLink>>> {
3245 self.request_lsp(
3246 buffer.clone(),
3247 LanguageServerToQuery::FirstCapable,
3248 GetTypeDefinition { position },
3249 cx,
3250 )
3251 }
3252
3253 pub fn type_definition<T: ToPointUtf16>(
3254 &mut self,
3255 buffer: &Entity<Buffer>,
3256 position: T,
3257 cx: &mut Context<Self>,
3258 ) -> Task<Result<Vec<LocationLink>>> {
3259 let position = position.to_point_utf16(buffer.read(cx));
3260 self.type_definition_impl(buffer, position, cx)
3261 }
3262
3263 pub fn implementation<T: ToPointUtf16>(
3264 &mut self,
3265 buffer: &Entity<Buffer>,
3266 position: T,
3267 cx: &mut Context<Self>,
3268 ) -> Task<Result<Vec<LocationLink>>> {
3269 let position = position.to_point_utf16(buffer.read(cx));
3270 self.request_lsp(
3271 buffer.clone(),
3272 LanguageServerToQuery::FirstCapable,
3273 GetImplementation { position },
3274 cx,
3275 )
3276 }
3277
3278 pub fn references<T: ToPointUtf16>(
3279 &mut self,
3280 buffer: &Entity<Buffer>,
3281 position: T,
3282 cx: &mut Context<Self>,
3283 ) -> Task<Result<Vec<Location>>> {
3284 let position = position.to_point_utf16(buffer.read(cx));
3285 self.request_lsp(
3286 buffer.clone(),
3287 LanguageServerToQuery::FirstCapable,
3288 GetReferences { position },
3289 cx,
3290 )
3291 }
3292
3293 fn document_highlights_impl(
3294 &mut self,
3295 buffer: &Entity<Buffer>,
3296 position: PointUtf16,
3297 cx: &mut Context<Self>,
3298 ) -> Task<Result<Vec<DocumentHighlight>>> {
3299 self.request_lsp(
3300 buffer.clone(),
3301 LanguageServerToQuery::FirstCapable,
3302 GetDocumentHighlights { position },
3303 cx,
3304 )
3305 }
3306
3307 pub fn document_highlights<T: ToPointUtf16>(
3308 &mut self,
3309 buffer: &Entity<Buffer>,
3310 position: T,
3311 cx: &mut Context<Self>,
3312 ) -> Task<Result<Vec<DocumentHighlight>>> {
3313 let position = position.to_point_utf16(buffer.read(cx));
3314 self.document_highlights_impl(buffer, position, cx)
3315 }
3316
3317 pub fn document_symbols(
3318 &mut self,
3319 buffer: &Entity<Buffer>,
3320 cx: &mut Context<Self>,
3321 ) -> Task<Result<Vec<DocumentSymbol>>> {
3322 self.request_lsp(
3323 buffer.clone(),
3324 LanguageServerToQuery::FirstCapable,
3325 GetDocumentSymbols,
3326 cx,
3327 )
3328 }
3329
3330 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
3331 self.lsp_store
3332 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3333 }
3334
3335 pub fn open_buffer_for_symbol(
3336 &mut self,
3337 symbol: &Symbol,
3338 cx: &mut Context<Self>,
3339 ) -> Task<Result<Entity<Buffer>>> {
3340 self.lsp_store.update(cx, |lsp_store, cx| {
3341 lsp_store.open_buffer_for_symbol(symbol, cx)
3342 })
3343 }
3344
3345 pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
3346 let guard = self.retain_remotely_created_models(cx);
3347 let Some(ssh_client) = self.ssh_client.as_ref() else {
3348 return Task::ready(Err(anyhow!("not an ssh project")));
3349 };
3350
3351 let proto_client = ssh_client.read(cx).proto_client();
3352
3353 cx.spawn(async move |project, cx| {
3354 let buffer = proto_client
3355 .request(proto::OpenServerSettings {
3356 project_id: SSH_PROJECT_ID,
3357 })
3358 .await?;
3359
3360 let buffer = project
3361 .update(cx, |project, cx| {
3362 project.buffer_store.update(cx, |buffer_store, cx| {
3363 anyhow::Ok(
3364 buffer_store
3365 .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
3366 )
3367 })
3368 })??
3369 .await;
3370
3371 drop(guard);
3372 buffer
3373 })
3374 }
3375
3376 pub fn open_local_buffer_via_lsp(
3377 &mut self,
3378 abs_path: lsp::Url,
3379 language_server_id: LanguageServerId,
3380 language_server_name: LanguageServerName,
3381 cx: &mut Context<Self>,
3382 ) -> Task<Result<Entity<Buffer>>> {
3383 self.lsp_store.update(cx, |lsp_store, cx| {
3384 lsp_store.open_local_buffer_via_lsp(
3385 abs_path,
3386 language_server_id,
3387 language_server_name,
3388 cx,
3389 )
3390 })
3391 }
3392
3393 pub fn signature_help<T: ToPointUtf16>(
3394 &self,
3395 buffer: &Entity<Buffer>,
3396 position: T,
3397 cx: &mut Context<Self>,
3398 ) -> Task<Vec<SignatureHelp>> {
3399 self.lsp_store.update(cx, |lsp_store, cx| {
3400 lsp_store.signature_help(buffer, position, cx)
3401 })
3402 }
3403
3404 pub fn hover<T: ToPointUtf16>(
3405 &self,
3406 buffer: &Entity<Buffer>,
3407 position: T,
3408 cx: &mut Context<Self>,
3409 ) -> Task<Vec<Hover>> {
3410 let position = position.to_point_utf16(buffer.read(cx));
3411 self.lsp_store
3412 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3413 }
3414
3415 pub fn linked_edit(
3416 &self,
3417 buffer: &Entity<Buffer>,
3418 position: Anchor,
3419 cx: &mut Context<Self>,
3420 ) -> Task<Result<Vec<Range<Anchor>>>> {
3421 self.lsp_store.update(cx, |lsp_store, cx| {
3422 lsp_store.linked_edit(buffer, position, cx)
3423 })
3424 }
3425
3426 pub fn completions<T: ToOffset + ToPointUtf16>(
3427 &self,
3428 buffer: &Entity<Buffer>,
3429 position: T,
3430 context: CompletionContext,
3431 cx: &mut Context<Self>,
3432 ) -> Task<Result<Option<Vec<Completion>>>> {
3433 let position = position.to_point_utf16(buffer.read(cx));
3434 self.lsp_store.update(cx, |lsp_store, cx| {
3435 lsp_store.completions(buffer, position, context, cx)
3436 })
3437 }
3438
3439 pub fn code_actions<T: Clone + ToOffset>(
3440 &mut self,
3441 buffer_handle: &Entity<Buffer>,
3442 range: Range<T>,
3443 kinds: Option<Vec<CodeActionKind>>,
3444 cx: &mut Context<Self>,
3445 ) -> Task<Result<Vec<CodeAction>>> {
3446 let buffer = buffer_handle.read(cx);
3447 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3448 self.lsp_store.update(cx, |lsp_store, cx| {
3449 lsp_store.code_actions(buffer_handle, range, kinds, cx)
3450 })
3451 }
3452
3453 pub fn code_lens<T: Clone + ToOffset>(
3454 &mut self,
3455 buffer_handle: &Entity<Buffer>,
3456 range: Range<T>,
3457 cx: &mut Context<Self>,
3458 ) -> Task<Result<Vec<CodeAction>>> {
3459 let snapshot = buffer_handle.read(cx).snapshot();
3460 let range = snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end);
3461 let code_lens_actions = self
3462 .lsp_store
3463 .update(cx, |lsp_store, cx| lsp_store.code_lens(buffer_handle, cx));
3464
3465 cx.background_spawn(async move {
3466 let mut code_lens_actions = code_lens_actions.await?;
3467 code_lens_actions.retain(|code_lens_action| {
3468 range
3469 .start
3470 .cmp(&code_lens_action.range.start, &snapshot)
3471 .is_ge()
3472 && range
3473 .end
3474 .cmp(&code_lens_action.range.end, &snapshot)
3475 .is_le()
3476 });
3477 Ok(code_lens_actions)
3478 })
3479 }
3480
3481 pub fn apply_code_action(
3482 &self,
3483 buffer_handle: Entity<Buffer>,
3484 action: CodeAction,
3485 push_to_history: bool,
3486 cx: &mut Context<Self>,
3487 ) -> Task<Result<ProjectTransaction>> {
3488 self.lsp_store.update(cx, |lsp_store, cx| {
3489 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3490 })
3491 }
3492
3493 pub fn apply_code_action_kind(
3494 &self,
3495 buffers: HashSet<Entity<Buffer>>,
3496 kind: CodeActionKind,
3497 push_to_history: bool,
3498 cx: &mut Context<Self>,
3499 ) -> Task<Result<ProjectTransaction>> {
3500 self.lsp_store.update(cx, |lsp_store, cx| {
3501 lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
3502 })
3503 }
3504
3505 fn prepare_rename_impl(
3506 &mut self,
3507 buffer: Entity<Buffer>,
3508 position: PointUtf16,
3509 cx: &mut Context<Self>,
3510 ) -> Task<Result<PrepareRenameResponse>> {
3511 self.request_lsp(
3512 buffer,
3513 LanguageServerToQuery::FirstCapable,
3514 PrepareRename { position },
3515 cx,
3516 )
3517 }
3518 pub fn prepare_rename<T: ToPointUtf16>(
3519 &mut self,
3520 buffer: Entity<Buffer>,
3521 position: T,
3522 cx: &mut Context<Self>,
3523 ) -> Task<Result<PrepareRenameResponse>> {
3524 let position = position.to_point_utf16(buffer.read(cx));
3525 self.prepare_rename_impl(buffer, position, cx)
3526 }
3527
3528 pub fn perform_rename<T: ToPointUtf16>(
3529 &mut self,
3530 buffer: Entity<Buffer>,
3531 position: T,
3532 new_name: String,
3533 cx: &mut Context<Self>,
3534 ) -> Task<Result<ProjectTransaction>> {
3535 let push_to_history = true;
3536 let position = position.to_point_utf16(buffer.read(cx));
3537 self.request_lsp(
3538 buffer,
3539 LanguageServerToQuery::FirstCapable,
3540 PerformRename {
3541 position,
3542 new_name,
3543 push_to_history,
3544 },
3545 cx,
3546 )
3547 }
3548
3549 pub fn on_type_format<T: ToPointUtf16>(
3550 &mut self,
3551 buffer: Entity<Buffer>,
3552 position: T,
3553 trigger: String,
3554 push_to_history: bool,
3555 cx: &mut Context<Self>,
3556 ) -> Task<Result<Option<Transaction>>> {
3557 self.lsp_store.update(cx, |lsp_store, cx| {
3558 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3559 })
3560 }
3561
3562 pub fn inline_values(
3563 &mut self,
3564 session: Entity<Session>,
3565 active_stack_frame: ActiveStackFrame,
3566 buffer_handle: Entity<Buffer>,
3567 range: Range<text::Anchor>,
3568 cx: &mut Context<Self>,
3569 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3570 let language_name = buffer_handle
3571 .read(cx)
3572 .language()
3573 .map(|language| language.name().to_string());
3574
3575 let Some(inline_value_provider) = language_name
3576 .and_then(|language| DapRegistry::global(cx).inline_value_provider(&language))
3577 else {
3578 return Task::ready(Err(anyhow::anyhow!("Inline value provider not found")));
3579 };
3580
3581 let snapshot = buffer_handle.read(cx).snapshot();
3582
3583 let Some(root_node) = snapshot.syntax_root_ancestor(range.end) else {
3584 return Task::ready(Ok(vec![]));
3585 };
3586
3587 let row = snapshot
3588 .summary_for_anchor::<text::PointUtf16>(&range.end)
3589 .row as usize;
3590
3591 let inline_value_locations = inline_value_provider.provide(
3592 root_node,
3593 snapshot
3594 .text_for_range(Anchor::MIN..range.end)
3595 .collect::<String>()
3596 .as_str(),
3597 row,
3598 );
3599
3600 let stack_frame_id = active_stack_frame.stack_frame_id;
3601 cx.spawn(async move |this, cx| {
3602 this.update(cx, |project, cx| {
3603 project.dap_store().update(cx, |dap_store, cx| {
3604 dap_store.resolve_inline_value_locations(
3605 session,
3606 stack_frame_id,
3607 buffer_handle,
3608 inline_value_locations,
3609 cx,
3610 )
3611 })
3612 })?
3613 .await
3614 })
3615 }
3616
3617 pub fn inlay_hints<T: ToOffset>(
3618 &mut self,
3619 buffer_handle: Entity<Buffer>,
3620 range: Range<T>,
3621 cx: &mut Context<Self>,
3622 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3623 let buffer = buffer_handle.read(cx);
3624 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3625 self.lsp_store.update(cx, |lsp_store, cx| {
3626 lsp_store.inlay_hints(buffer_handle, range, cx)
3627 })
3628 }
3629
3630 pub fn resolve_inlay_hint(
3631 &self,
3632 hint: InlayHint,
3633 buffer_handle: Entity<Buffer>,
3634 server_id: LanguageServerId,
3635 cx: &mut Context<Self>,
3636 ) -> Task<anyhow::Result<InlayHint>> {
3637 self.lsp_store.update(cx, |lsp_store, cx| {
3638 lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3639 })
3640 }
3641
3642 pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
3643 let (result_tx, result_rx) = smol::channel::unbounded();
3644
3645 let matching_buffers_rx = if query.is_opened_only() {
3646 self.sort_search_candidates(&query, cx)
3647 } else {
3648 self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3649 };
3650
3651 cx.spawn(async move |_, cx| {
3652 let mut range_count = 0;
3653 let mut buffer_count = 0;
3654 let mut limit_reached = false;
3655 let query = Arc::new(query);
3656 let chunks = matching_buffers_rx.ready_chunks(64);
3657
3658 // Now that we know what paths match the query, we will load at most
3659 // 64 buffers at a time to avoid overwhelming the main thread. For each
3660 // opened buffer, we will spawn a background task that retrieves all the
3661 // ranges in the buffer matched by the query.
3662 let mut chunks = pin!(chunks);
3663 'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3664 let mut chunk_results = Vec::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_with(cx, |worktree_store, cx| {
3874 worktree_store.find_worktree(abs_path, cx)
3875 })
3876 }
3877
3878 pub fn is_shared(&self) -> bool {
3879 match &self.client_state {
3880 ProjectClientState::Shared { .. } => true,
3881 ProjectClientState::Local => false,
3882 ProjectClientState::Remote { .. } => true,
3883 }
3884 }
3885
3886 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3887 pub fn resolve_path_in_buffer(
3888 &self,
3889 path: &str,
3890 buffer: &Entity<Buffer>,
3891 cx: &mut Context<Self>,
3892 ) -> Task<Option<ResolvedPath>> {
3893 let path_buf = PathBuf::from(path);
3894 if path_buf.is_absolute() || path.starts_with("~") {
3895 self.resolve_abs_path(path, cx)
3896 } else {
3897 self.resolve_path_in_worktrees(path_buf, buffer, cx)
3898 }
3899 }
3900
3901 pub fn resolve_abs_file_path(
3902 &self,
3903 path: &str,
3904 cx: &mut Context<Self>,
3905 ) -> Task<Option<ResolvedPath>> {
3906 let resolve_task = self.resolve_abs_path(path, cx);
3907 cx.background_spawn(async move {
3908 let resolved_path = resolve_task.await;
3909 resolved_path.filter(|path| path.is_file())
3910 })
3911 }
3912
3913 pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
3914 if self.is_local() {
3915 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3916 let fs = self.fs.clone();
3917 cx.background_spawn(async move {
3918 let path = expanded.as_path();
3919 let metadata = fs.metadata(path).await.ok().flatten();
3920
3921 metadata.map(|metadata| ResolvedPath::AbsPath {
3922 path: expanded,
3923 is_dir: metadata.is_dir,
3924 })
3925 })
3926 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3927 let request_path = Path::new(path);
3928 let request = ssh_client
3929 .read(cx)
3930 .proto_client()
3931 .request(proto::GetPathMetadata {
3932 project_id: SSH_PROJECT_ID,
3933 path: request_path.to_proto(),
3934 });
3935 cx.background_spawn(async move {
3936 let response = request.await.log_err()?;
3937 if response.exists {
3938 Some(ResolvedPath::AbsPath {
3939 path: PathBuf::from_proto(response.path),
3940 is_dir: response.is_dir,
3941 })
3942 } else {
3943 None
3944 }
3945 })
3946 } else {
3947 return Task::ready(None);
3948 }
3949 }
3950
3951 fn resolve_path_in_worktrees(
3952 &self,
3953 path: PathBuf,
3954 buffer: &Entity<Buffer>,
3955 cx: &mut Context<Self>,
3956 ) -> Task<Option<ResolvedPath>> {
3957 let mut candidates = vec![path.clone()];
3958
3959 if let Some(file) = buffer.read(cx).file() {
3960 if let Some(dir) = file.path().parent() {
3961 let joined = dir.to_path_buf().join(path);
3962 candidates.push(joined);
3963 }
3964 }
3965
3966 let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
3967 let worktrees_with_ids: Vec<_> = self
3968 .worktrees(cx)
3969 .map(|worktree| {
3970 let id = worktree.read(cx).id();
3971 (worktree, id)
3972 })
3973 .collect();
3974
3975 cx.spawn(async move |_, mut cx| {
3976 if let Some(buffer_worktree_id) = buffer_worktree_id {
3977 if let Some((worktree, _)) = worktrees_with_ids
3978 .iter()
3979 .find(|(_, id)| *id == buffer_worktree_id)
3980 {
3981 for candidate in candidates.iter() {
3982 if let Some(path) =
3983 Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3984 {
3985 return Some(path);
3986 }
3987 }
3988 }
3989 }
3990 for (worktree, id) in worktrees_with_ids {
3991 if Some(id) == buffer_worktree_id {
3992 continue;
3993 }
3994 for candidate in candidates.iter() {
3995 if let Some(path) =
3996 Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3997 {
3998 return Some(path);
3999 }
4000 }
4001 }
4002 None
4003 })
4004 }
4005
4006 fn resolve_path_in_worktree(
4007 worktree: &Entity<Worktree>,
4008 path: &PathBuf,
4009 cx: &mut AsyncApp,
4010 ) -> Option<ResolvedPath> {
4011 worktree
4012 .update(cx, |worktree, _| {
4013 let root_entry_path = &worktree.root_entry()?.path;
4014 let resolved = resolve_path(root_entry_path, path);
4015 let stripped = resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
4016 worktree.entry_for_path(stripped).map(|entry| {
4017 let project_path = ProjectPath {
4018 worktree_id: worktree.id(),
4019 path: entry.path.clone(),
4020 };
4021 ResolvedPath::ProjectPath {
4022 project_path,
4023 is_dir: entry.is_dir(),
4024 }
4025 })
4026 })
4027 .ok()?
4028 }
4029
4030 pub fn list_directory(
4031 &self,
4032 query: String,
4033 cx: &mut Context<Self>,
4034 ) -> Task<Result<Vec<DirectoryItem>>> {
4035 if self.is_local() {
4036 DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
4037 } else if let Some(session) = self.ssh_client.as_ref() {
4038 let path_buf = PathBuf::from(query);
4039 let request = proto::ListRemoteDirectory {
4040 dev_server_id: SSH_PROJECT_ID,
4041 path: path_buf.to_proto(),
4042 config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4043 };
4044
4045 let response = session.read(cx).proto_client().request(request);
4046 cx.background_spawn(async move {
4047 let proto::ListRemoteDirectoryResponse {
4048 entries,
4049 entry_info,
4050 } = response.await?;
4051 Ok(entries
4052 .into_iter()
4053 .zip(entry_info)
4054 .map(|(entry, info)| DirectoryItem {
4055 path: PathBuf::from(entry),
4056 is_dir: info.is_dir,
4057 })
4058 .collect())
4059 })
4060 } else {
4061 Task::ready(Err(anyhow!("cannot list directory in remote project")))
4062 }
4063 }
4064
4065 pub fn create_worktree(
4066 &mut self,
4067 abs_path: impl AsRef<Path>,
4068 visible: bool,
4069 cx: &mut Context<Self>,
4070 ) -> Task<Result<Entity<Worktree>>> {
4071 self.worktree_store.update(cx, |worktree_store, cx| {
4072 worktree_store.create_worktree(abs_path, visible, cx)
4073 })
4074 }
4075
4076 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4077 self.worktree_store.update(cx, |worktree_store, cx| {
4078 worktree_store.remove_worktree(id_to_remove, cx);
4079 });
4080 }
4081
4082 fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4083 self.worktree_store.update(cx, |worktree_store, cx| {
4084 worktree_store.add(worktree, cx);
4085 });
4086 }
4087
4088 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4089 let new_active_entry = entry.and_then(|project_path| {
4090 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4091 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4092 Some(entry.id)
4093 });
4094 if new_active_entry != self.active_entry {
4095 self.active_entry = new_active_entry;
4096 self.lsp_store.update(cx, |lsp_store, _| {
4097 lsp_store.set_active_entry(new_active_entry);
4098 });
4099 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4100 }
4101 }
4102
4103 pub fn language_servers_running_disk_based_diagnostics<'a>(
4104 &'a self,
4105 cx: &'a App,
4106 ) -> impl Iterator<Item = LanguageServerId> + 'a {
4107 self.lsp_store
4108 .read(cx)
4109 .language_servers_running_disk_based_diagnostics()
4110 }
4111
4112 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4113 self.lsp_store
4114 .read(cx)
4115 .diagnostic_summary(include_ignored, cx)
4116 }
4117
4118 pub fn diagnostic_summaries<'a>(
4119 &'a self,
4120 include_ignored: bool,
4121 cx: &'a App,
4122 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4123 self.lsp_store
4124 .read(cx)
4125 .diagnostic_summaries(include_ignored, cx)
4126 }
4127
4128 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4129 self.active_entry
4130 }
4131
4132 pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
4133 self.worktree_store.read(cx).entry_for_path(path, cx)
4134 }
4135
4136 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4137 let worktree = self.worktree_for_entry(entry_id, cx)?;
4138 let worktree = worktree.read(cx);
4139 let worktree_id = worktree.id();
4140 let path = worktree.entry_for_id(entry_id)?.path.clone();
4141 Some(ProjectPath { worktree_id, path })
4142 }
4143
4144 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4145 self.worktree_for_id(project_path.worktree_id, cx)?
4146 .read(cx)
4147 .absolutize(&project_path.path)
4148 .ok()
4149 }
4150
4151 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4152 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4153 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4154 /// the first visible worktree that has an entry for that relative path.
4155 ///
4156 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4157 /// root name from paths.
4158 ///
4159 /// # Arguments
4160 ///
4161 /// * `path` - A full path that starts with a worktree root name, or alternatively a
4162 /// relative path within a visible worktree.
4163 /// * `cx` - A reference to the `AppContext`.
4164 ///
4165 /// # Returns
4166 ///
4167 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4168 pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4169 let path = path.as_ref();
4170 let worktree_store = self.worktree_store.read(cx);
4171
4172 if path.is_absolute() {
4173 for worktree in worktree_store.visible_worktrees(cx) {
4174 let worktree_abs_path = worktree.read(cx).abs_path();
4175
4176 if let Ok(relative_path) = path.strip_prefix(worktree_abs_path) {
4177 return Some(ProjectPath {
4178 worktree_id: worktree.read(cx).id(),
4179 path: relative_path.into(),
4180 });
4181 }
4182 }
4183 } else {
4184 for worktree in worktree_store.visible_worktrees(cx) {
4185 let worktree_root_name = worktree.read(cx).root_name();
4186 if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
4187 return Some(ProjectPath {
4188 worktree_id: worktree.read(cx).id(),
4189 path: relative_path.into(),
4190 });
4191 }
4192 }
4193
4194 for worktree in worktree_store.visible_worktrees(cx) {
4195 let worktree = worktree.read(cx);
4196 if let Some(entry) = worktree.entry_for_path(path) {
4197 return Some(ProjectPath {
4198 worktree_id: worktree.id(),
4199 path: entry.path.clone(),
4200 });
4201 }
4202 }
4203 }
4204
4205 None
4206 }
4207
4208 pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4209 self.find_worktree(abs_path, cx)
4210 .map(|(worktree, relative_path)| ProjectPath {
4211 worktree_id: worktree.read(cx).id(),
4212 path: relative_path.into(),
4213 })
4214 }
4215
4216 pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4217 Some(
4218 self.worktree_for_id(project_path.worktree_id, cx)?
4219 .read(cx)
4220 .abs_path()
4221 .to_path_buf(),
4222 )
4223 }
4224
4225 pub fn blame_buffer(
4226 &self,
4227 buffer: &Entity<Buffer>,
4228 version: Option<clock::Global>,
4229 cx: &mut App,
4230 ) -> Task<Result<Option<Blame>>> {
4231 self.git_store.update(cx, |git_store, cx| {
4232 git_store.blame_buffer(buffer, version, cx)
4233 })
4234 }
4235
4236 pub fn get_permalink_to_line(
4237 &self,
4238 buffer: &Entity<Buffer>,
4239 selection: Range<u32>,
4240 cx: &mut App,
4241 ) -> Task<Result<url::Url>> {
4242 self.git_store.update(cx, |git_store, cx| {
4243 git_store.get_permalink_to_line(buffer, selection, cx)
4244 })
4245 }
4246
4247 // RPC message handlers
4248
4249 async fn handle_unshare_project(
4250 this: Entity<Self>,
4251 _: TypedEnvelope<proto::UnshareProject>,
4252 mut cx: AsyncApp,
4253 ) -> Result<()> {
4254 this.update(&mut cx, |this, cx| {
4255 if this.is_local() || this.is_via_ssh() {
4256 this.unshare(cx)?;
4257 } else {
4258 this.disconnected_from_host(cx);
4259 }
4260 Ok(())
4261 })?
4262 }
4263
4264 async fn handle_add_collaborator(
4265 this: Entity<Self>,
4266 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4267 mut cx: AsyncApp,
4268 ) -> Result<()> {
4269 let collaborator = envelope
4270 .payload
4271 .collaborator
4272 .take()
4273 .context("empty collaborator")?;
4274
4275 let collaborator = Collaborator::from_proto(collaborator)?;
4276 this.update(&mut cx, |this, cx| {
4277 this.buffer_store.update(cx, |buffer_store, _| {
4278 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4279 });
4280 this.breakpoint_store.read(cx).broadcast();
4281 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4282 this.collaborators
4283 .insert(collaborator.peer_id, collaborator);
4284 })?;
4285
4286 Ok(())
4287 }
4288
4289 async fn handle_update_project_collaborator(
4290 this: Entity<Self>,
4291 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4292 mut cx: AsyncApp,
4293 ) -> Result<()> {
4294 let old_peer_id = envelope
4295 .payload
4296 .old_peer_id
4297 .context("missing old peer id")?;
4298 let new_peer_id = envelope
4299 .payload
4300 .new_peer_id
4301 .context("missing new peer id")?;
4302 this.update(&mut cx, |this, cx| {
4303 let collaborator = this
4304 .collaborators
4305 .remove(&old_peer_id)
4306 .context("received UpdateProjectCollaborator for unknown peer")?;
4307 let is_host = collaborator.is_host;
4308 this.collaborators.insert(new_peer_id, collaborator);
4309
4310 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4311 this.buffer_store.update(cx, |buffer_store, _| {
4312 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4313 });
4314
4315 if is_host {
4316 this.buffer_store
4317 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4318 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4319 .unwrap();
4320 cx.emit(Event::HostReshared);
4321 }
4322
4323 cx.emit(Event::CollaboratorUpdated {
4324 old_peer_id,
4325 new_peer_id,
4326 });
4327 Ok(())
4328 })?
4329 }
4330
4331 async fn handle_remove_collaborator(
4332 this: Entity<Self>,
4333 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4334 mut cx: AsyncApp,
4335 ) -> Result<()> {
4336 this.update(&mut cx, |this, cx| {
4337 let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
4338 let replica_id = this
4339 .collaborators
4340 .remove(&peer_id)
4341 .with_context(|| format!("unknown peer {peer_id:?}"))?
4342 .replica_id;
4343 this.buffer_store.update(cx, |buffer_store, cx| {
4344 buffer_store.forget_shared_buffers_for(&peer_id);
4345 for buffer in buffer_store.buffers() {
4346 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4347 }
4348 });
4349 this.git_store.update(cx, |git_store, _| {
4350 git_store.forget_shared_diffs_for(&peer_id);
4351 });
4352
4353 cx.emit(Event::CollaboratorLeft(peer_id));
4354 Ok(())
4355 })?
4356 }
4357
4358 async fn handle_update_project(
4359 this: Entity<Self>,
4360 envelope: TypedEnvelope<proto::UpdateProject>,
4361 mut cx: AsyncApp,
4362 ) -> Result<()> {
4363 this.update(&mut cx, |this, cx| {
4364 // Don't handle messages that were sent before the response to us joining the project
4365 if envelope.message_id > this.join_project_response_message_id {
4366 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4367 }
4368 Ok(())
4369 })?
4370 }
4371
4372 async fn handle_toast(
4373 this: Entity<Self>,
4374 envelope: TypedEnvelope<proto::Toast>,
4375 mut cx: AsyncApp,
4376 ) -> Result<()> {
4377 this.update(&mut cx, |_, cx| {
4378 cx.emit(Event::Toast {
4379 notification_id: envelope.payload.notification_id.into(),
4380 message: envelope.payload.message,
4381 });
4382 Ok(())
4383 })?
4384 }
4385
4386 async fn handle_language_server_prompt_request(
4387 this: Entity<Self>,
4388 envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4389 mut cx: AsyncApp,
4390 ) -> Result<proto::LanguageServerPromptResponse> {
4391 let (tx, rx) = smol::channel::bounded(1);
4392 let actions: Vec<_> = envelope
4393 .payload
4394 .actions
4395 .into_iter()
4396 .map(|action| MessageActionItem {
4397 title: action,
4398 properties: Default::default(),
4399 })
4400 .collect();
4401 this.update(&mut cx, |_, cx| {
4402 cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4403 level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4404 message: envelope.payload.message,
4405 actions: actions.clone(),
4406 lsp_name: envelope.payload.lsp_name,
4407 response_channel: tx,
4408 }));
4409
4410 anyhow::Ok(())
4411 })??;
4412
4413 // We drop `this` to avoid holding a reference in this future for too
4414 // long.
4415 // If we keep the reference, we might not drop the `Project` early
4416 // enough when closing a window and it will only get releases on the
4417 // next `flush_effects()` call.
4418 drop(this);
4419
4420 let mut rx = pin!(rx);
4421 let answer = rx.next().await;
4422
4423 Ok(LanguageServerPromptResponse {
4424 action_response: answer.and_then(|answer| {
4425 actions
4426 .iter()
4427 .position(|action| *action == answer)
4428 .map(|index| index as u64)
4429 }),
4430 })
4431 }
4432
4433 async fn handle_hide_toast(
4434 this: Entity<Self>,
4435 envelope: TypedEnvelope<proto::HideToast>,
4436 mut cx: AsyncApp,
4437 ) -> Result<()> {
4438 this.update(&mut cx, |_, cx| {
4439 cx.emit(Event::HideToast {
4440 notification_id: envelope.payload.notification_id.into(),
4441 });
4442 Ok(())
4443 })?
4444 }
4445
4446 // Collab sends UpdateWorktree protos as messages
4447 async fn handle_update_worktree(
4448 this: Entity<Self>,
4449 envelope: TypedEnvelope<proto::UpdateWorktree>,
4450 mut cx: AsyncApp,
4451 ) -> Result<()> {
4452 this.update(&mut cx, |this, cx| {
4453 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4454 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4455 worktree.update(cx, |worktree, _| {
4456 let worktree = worktree.as_remote_mut().unwrap();
4457 worktree.update_from_remote(envelope.payload);
4458 });
4459 }
4460 Ok(())
4461 })?
4462 }
4463
4464 async fn handle_update_buffer_from_ssh(
4465 this: Entity<Self>,
4466 envelope: TypedEnvelope<proto::UpdateBuffer>,
4467 cx: AsyncApp,
4468 ) -> Result<proto::Ack> {
4469 let buffer_store = this.read_with(&cx, |this, cx| {
4470 if let Some(remote_id) = this.remote_id() {
4471 let mut payload = envelope.payload.clone();
4472 payload.project_id = remote_id;
4473 cx.background_spawn(this.client.request(payload))
4474 .detach_and_log_err(cx);
4475 }
4476 this.buffer_store.clone()
4477 })?;
4478 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4479 }
4480
4481 async fn handle_update_buffer(
4482 this: Entity<Self>,
4483 envelope: TypedEnvelope<proto::UpdateBuffer>,
4484 cx: AsyncApp,
4485 ) -> Result<proto::Ack> {
4486 let buffer_store = this.read_with(&cx, |this, cx| {
4487 if let Some(ssh) = &this.ssh_client {
4488 let mut payload = envelope.payload.clone();
4489 payload.project_id = SSH_PROJECT_ID;
4490 cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4491 .detach_and_log_err(cx);
4492 }
4493 this.buffer_store.clone()
4494 })?;
4495 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4496 }
4497
4498 fn retain_remotely_created_models(
4499 &mut self,
4500 cx: &mut Context<Self>,
4501 ) -> RemotelyCreatedModelGuard {
4502 {
4503 let mut remotely_create_models = self.remotely_created_models.lock();
4504 if remotely_create_models.retain_count == 0 {
4505 remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
4506 remotely_create_models.worktrees =
4507 self.worktree_store.read(cx).worktrees().collect();
4508 }
4509 remotely_create_models.retain_count += 1;
4510 }
4511 RemotelyCreatedModelGuard {
4512 remote_models: Arc::downgrade(&self.remotely_created_models),
4513 }
4514 }
4515
4516 async fn handle_create_buffer_for_peer(
4517 this: Entity<Self>,
4518 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4519 mut cx: AsyncApp,
4520 ) -> Result<()> {
4521 this.update(&mut cx, |this, cx| {
4522 this.buffer_store.update(cx, |buffer_store, cx| {
4523 buffer_store.handle_create_buffer_for_peer(
4524 envelope,
4525 this.replica_id(),
4526 this.capability(),
4527 cx,
4528 )
4529 })
4530 })?
4531 }
4532
4533 async fn handle_synchronize_buffers(
4534 this: Entity<Self>,
4535 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4536 mut cx: AsyncApp,
4537 ) -> Result<proto::SynchronizeBuffersResponse> {
4538 let response = this.update(&mut cx, |this, cx| {
4539 let client = this.client.clone();
4540 this.buffer_store.update(cx, |this, cx| {
4541 this.handle_synchronize_buffers(envelope, cx, client)
4542 })
4543 })??;
4544
4545 Ok(response)
4546 }
4547
4548 async fn handle_search_candidate_buffers(
4549 this: Entity<Self>,
4550 envelope: TypedEnvelope<proto::FindSearchCandidates>,
4551 mut cx: AsyncApp,
4552 ) -> Result<proto::FindSearchCandidatesResponse> {
4553 let peer_id = envelope.original_sender_id()?;
4554 let message = envelope.payload;
4555 let query = SearchQuery::from_proto(message.query.context("missing query field")?)?;
4556 let results = this.update(&mut cx, |this, cx| {
4557 this.find_search_candidate_buffers(&query, message.limit as _, cx)
4558 })?;
4559
4560 let mut response = proto::FindSearchCandidatesResponse {
4561 buffer_ids: Vec::new(),
4562 };
4563
4564 while let Ok(buffer) = results.recv().await {
4565 this.update(&mut cx, |this, cx| {
4566 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4567 response.buffer_ids.push(buffer_id.to_proto());
4568 })?;
4569 }
4570
4571 Ok(response)
4572 }
4573
4574 async fn handle_open_buffer_by_id(
4575 this: Entity<Self>,
4576 envelope: TypedEnvelope<proto::OpenBufferById>,
4577 mut cx: AsyncApp,
4578 ) -> Result<proto::OpenBufferResponse> {
4579 let peer_id = envelope.original_sender_id()?;
4580 let buffer_id = BufferId::new(envelope.payload.id)?;
4581 let buffer = this
4582 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4583 .await?;
4584 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4585 }
4586
4587 async fn handle_open_buffer_by_path(
4588 this: Entity<Self>,
4589 envelope: TypedEnvelope<proto::OpenBufferByPath>,
4590 mut cx: AsyncApp,
4591 ) -> Result<proto::OpenBufferResponse> {
4592 let peer_id = envelope.original_sender_id()?;
4593 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4594 let open_buffer = this.update(&mut cx, |this, cx| {
4595 this.open_buffer(
4596 ProjectPath {
4597 worktree_id,
4598 path: Arc::<Path>::from_proto(envelope.payload.path),
4599 },
4600 cx,
4601 )
4602 })?;
4603
4604 let buffer = open_buffer.await?;
4605 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4606 }
4607
4608 async fn handle_open_new_buffer(
4609 this: Entity<Self>,
4610 envelope: TypedEnvelope<proto::OpenNewBuffer>,
4611 mut cx: AsyncApp,
4612 ) -> Result<proto::OpenBufferResponse> {
4613 let buffer = this
4614 .update(&mut cx, |this, cx| this.create_buffer(cx))?
4615 .await?;
4616 let peer_id = envelope.original_sender_id()?;
4617
4618 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4619 }
4620
4621 fn respond_to_open_buffer_request(
4622 this: Entity<Self>,
4623 buffer: Entity<Buffer>,
4624 peer_id: proto::PeerId,
4625 cx: &mut AsyncApp,
4626 ) -> Result<proto::OpenBufferResponse> {
4627 this.update(cx, |this, cx| {
4628 let is_private = buffer
4629 .read(cx)
4630 .file()
4631 .map(|f| f.is_private())
4632 .unwrap_or_default();
4633 anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
4634 Ok(proto::OpenBufferResponse {
4635 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4636 })
4637 })?
4638 }
4639
4640 fn create_buffer_for_peer(
4641 &mut self,
4642 buffer: &Entity<Buffer>,
4643 peer_id: proto::PeerId,
4644 cx: &mut App,
4645 ) -> BufferId {
4646 self.buffer_store
4647 .update(cx, |buffer_store, cx| {
4648 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4649 })
4650 .detach_and_log_err(cx);
4651 buffer.read(cx).remote_id()
4652 }
4653
4654 fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4655 let project_id = match self.client_state {
4656 ProjectClientState::Remote {
4657 sharing_has_stopped,
4658 remote_id,
4659 ..
4660 } => {
4661 if sharing_has_stopped {
4662 return Task::ready(Err(anyhow!(
4663 "can't synchronize remote buffers on a readonly project"
4664 )));
4665 } else {
4666 remote_id
4667 }
4668 }
4669 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4670 return Task::ready(Err(anyhow!(
4671 "can't synchronize remote buffers on a local project"
4672 )));
4673 }
4674 };
4675
4676 let client = self.client.clone();
4677 cx.spawn(async move |this, cx| {
4678 let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
4679 this.buffer_store.read(cx).buffer_version_info(cx)
4680 })?;
4681 let response = client
4682 .request(proto::SynchronizeBuffers {
4683 project_id,
4684 buffers,
4685 })
4686 .await?;
4687
4688 let send_updates_for_buffers = this.update(cx, |this, cx| {
4689 response
4690 .buffers
4691 .into_iter()
4692 .map(|buffer| {
4693 let client = client.clone();
4694 let buffer_id = match BufferId::new(buffer.id) {
4695 Ok(id) => id,
4696 Err(e) => {
4697 return Task::ready(Err(e));
4698 }
4699 };
4700 let remote_version = language::proto::deserialize_version(&buffer.version);
4701 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4702 let operations =
4703 buffer.read(cx).serialize_ops(Some(remote_version), cx);
4704 cx.background_spawn(async move {
4705 let operations = operations.await;
4706 for chunk in split_operations(operations) {
4707 client
4708 .request(proto::UpdateBuffer {
4709 project_id,
4710 buffer_id: buffer_id.into(),
4711 operations: chunk,
4712 })
4713 .await?;
4714 }
4715 anyhow::Ok(())
4716 })
4717 } else {
4718 Task::ready(Ok(()))
4719 }
4720 })
4721 .collect::<Vec<_>>()
4722 })?;
4723
4724 // Any incomplete buffers have open requests waiting. Request that the host sends
4725 // creates these buffers for us again to unblock any waiting futures.
4726 for id in incomplete_buffer_ids {
4727 cx.background_spawn(client.request(proto::OpenBufferById {
4728 project_id,
4729 id: id.into(),
4730 }))
4731 .detach();
4732 }
4733
4734 futures::future::join_all(send_updates_for_buffers)
4735 .await
4736 .into_iter()
4737 .collect()
4738 })
4739 }
4740
4741 pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4742 self.worktree_store.read(cx).worktree_metadata_protos(cx)
4743 }
4744
4745 /// Iterator of all open buffers that have unsaved changes
4746 pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4747 self.buffer_store.read(cx).buffers().filter_map(|buf| {
4748 let buf = buf.read(cx);
4749 if buf.is_dirty() {
4750 buf.project_path(cx)
4751 } else {
4752 None
4753 }
4754 })
4755 }
4756
4757 fn set_worktrees_from_proto(
4758 &mut self,
4759 worktrees: Vec<proto::WorktreeMetadata>,
4760 cx: &mut Context<Project>,
4761 ) -> Result<()> {
4762 self.worktree_store.update(cx, |worktree_store, cx| {
4763 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4764 })
4765 }
4766
4767 fn set_collaborators_from_proto(
4768 &mut self,
4769 messages: Vec<proto::Collaborator>,
4770 cx: &mut Context<Self>,
4771 ) -> Result<()> {
4772 let mut collaborators = HashMap::default();
4773 for message in messages {
4774 let collaborator = Collaborator::from_proto(message)?;
4775 collaborators.insert(collaborator.peer_id, collaborator);
4776 }
4777 for old_peer_id in self.collaborators.keys() {
4778 if !collaborators.contains_key(old_peer_id) {
4779 cx.emit(Event::CollaboratorLeft(*old_peer_id));
4780 }
4781 }
4782 self.collaborators = collaborators;
4783 Ok(())
4784 }
4785
4786 pub fn supplementary_language_servers<'a>(
4787 &'a self,
4788 cx: &'a App,
4789 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4790 self.lsp_store.read(cx).supplementary_language_servers()
4791 }
4792
4793 pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
4794 self.lsp_store.update(cx, |this, cx| {
4795 this.language_servers_for_local_buffer(buffer, cx)
4796 .any(
4797 |(_, server)| match server.capabilities().inlay_hint_provider {
4798 Some(lsp::OneOf::Left(enabled)) => enabled,
4799 Some(lsp::OneOf::Right(_)) => true,
4800 None => false,
4801 },
4802 )
4803 })
4804 }
4805
4806 pub fn language_server_id_for_name(
4807 &self,
4808 buffer: &Buffer,
4809 name: &str,
4810 cx: &mut App,
4811 ) -> Task<Option<LanguageServerId>> {
4812 if self.is_local() {
4813 Task::ready(self.lsp_store.update(cx, |lsp_store, cx| {
4814 lsp_store
4815 .language_servers_for_local_buffer(buffer, cx)
4816 .find_map(|(adapter, server)| {
4817 if adapter.name.0 == name {
4818 Some(server.server_id())
4819 } else {
4820 None
4821 }
4822 })
4823 }))
4824 } else if let Some(project_id) = self.remote_id() {
4825 let request = self.client.request(proto::LanguageServerIdForName {
4826 project_id,
4827 buffer_id: buffer.remote_id().to_proto(),
4828 name: name.to_string(),
4829 });
4830 cx.background_spawn(async move {
4831 let response = request.await.log_err()?;
4832 response.server_id.map(LanguageServerId::from_proto)
4833 })
4834 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
4835 let request =
4836 ssh_client
4837 .read(cx)
4838 .proto_client()
4839 .request(proto::LanguageServerIdForName {
4840 project_id: SSH_PROJECT_ID,
4841 buffer_id: buffer.remote_id().to_proto(),
4842 name: name.to_string(),
4843 });
4844 cx.background_spawn(async move {
4845 let response = request.await.log_err()?;
4846 response.server_id.map(LanguageServerId::from_proto)
4847 })
4848 } else {
4849 Task::ready(None)
4850 }
4851 }
4852
4853 pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
4854 self.lsp_store.update(cx, |this, cx| {
4855 this.language_servers_for_local_buffer(buffer, cx)
4856 .next()
4857 .is_some()
4858 })
4859 }
4860
4861 pub fn git_init(
4862 &self,
4863 path: Arc<Path>,
4864 fallback_branch_name: String,
4865 cx: &App,
4866 ) -> Task<Result<()>> {
4867 self.git_store
4868 .read(cx)
4869 .git_init(path, fallback_branch_name, cx)
4870 }
4871
4872 pub fn buffer_store(&self) -> &Entity<BufferStore> {
4873 &self.buffer_store
4874 }
4875
4876 pub fn git_store(&self) -> &Entity<GitStore> {
4877 &self.git_store
4878 }
4879
4880 #[cfg(test)]
4881 fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
4882 cx.spawn(async move |this, cx| {
4883 let scans_complete = this
4884 .read_with(cx, |this, cx| {
4885 this.worktrees(cx)
4886 .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
4887 .collect::<Vec<_>>()
4888 })
4889 .unwrap();
4890 join_all(scans_complete).await;
4891 let barriers = this
4892 .update(cx, |this, cx| {
4893 let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
4894 repos
4895 .into_iter()
4896 .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
4897 .collect::<Vec<_>>()
4898 })
4899 .unwrap();
4900 join_all(barriers).await;
4901 })
4902 }
4903
4904 pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
4905 self.git_store.read(cx).active_repository()
4906 }
4907
4908 pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
4909 self.git_store.read(cx).repositories()
4910 }
4911
4912 pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
4913 self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
4914 }
4915
4916 pub fn set_agent_location(
4917 &mut self,
4918 new_location: Option<AgentLocation>,
4919 cx: &mut Context<Self>,
4920 ) {
4921 if let Some(old_location) = self.agent_location.as_ref() {
4922 old_location
4923 .buffer
4924 .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
4925 .ok();
4926 }
4927
4928 if let Some(location) = new_location.as_ref() {
4929 location
4930 .buffer
4931 .update(cx, |buffer, cx| {
4932 buffer.set_agent_selections(
4933 Arc::from([language::Selection {
4934 id: 0,
4935 start: location.position,
4936 end: location.position,
4937 reversed: false,
4938 goal: language::SelectionGoal::None,
4939 }]),
4940 false,
4941 CursorShape::Hollow,
4942 cx,
4943 )
4944 })
4945 .ok();
4946 }
4947
4948 self.agent_location = new_location;
4949 cx.emit(Event::AgentLocationChanged);
4950 }
4951
4952 pub fn agent_location(&self) -> Option<AgentLocation> {
4953 self.agent_location.clone()
4954 }
4955}
4956
4957pub struct PathMatchCandidateSet {
4958 pub snapshot: Snapshot,
4959 pub include_ignored: bool,
4960 pub include_root_name: bool,
4961 pub candidates: Candidates,
4962}
4963
4964pub enum Candidates {
4965 /// Only consider directories.
4966 Directories,
4967 /// Only consider files.
4968 Files,
4969 /// Consider directories and files.
4970 Entries,
4971}
4972
4973impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4974 type Candidates = PathMatchCandidateSetIter<'a>;
4975
4976 fn id(&self) -> usize {
4977 self.snapshot.id().to_usize()
4978 }
4979
4980 fn len(&self) -> usize {
4981 match self.candidates {
4982 Candidates::Files => {
4983 if self.include_ignored {
4984 self.snapshot.file_count()
4985 } else {
4986 self.snapshot.visible_file_count()
4987 }
4988 }
4989
4990 Candidates::Directories => {
4991 if self.include_ignored {
4992 self.snapshot.dir_count()
4993 } else {
4994 self.snapshot.visible_dir_count()
4995 }
4996 }
4997
4998 Candidates::Entries => {
4999 if self.include_ignored {
5000 self.snapshot.entry_count()
5001 } else {
5002 self.snapshot.visible_entry_count()
5003 }
5004 }
5005 }
5006 }
5007
5008 fn prefix(&self) -> Arc<str> {
5009 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5010 self.snapshot.root_name().into()
5011 } else if self.include_root_name {
5012 format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
5013 } else {
5014 Arc::default()
5015 }
5016 }
5017
5018 fn candidates(&'a self, start: usize) -> Self::Candidates {
5019 PathMatchCandidateSetIter {
5020 traversal: match self.candidates {
5021 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5022 Candidates::Files => self.snapshot.files(self.include_ignored, start),
5023 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5024 },
5025 }
5026 }
5027}
5028
5029pub struct PathMatchCandidateSetIter<'a> {
5030 traversal: Traversal<'a>,
5031}
5032
5033impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5034 type Item = fuzzy::PathMatchCandidate<'a>;
5035
5036 fn next(&mut self) -> Option<Self::Item> {
5037 self.traversal
5038 .next()
5039 .map(|entry| fuzzy::PathMatchCandidate {
5040 is_dir: entry.kind.is_dir(),
5041 path: &entry.path,
5042 char_bag: entry.char_bag,
5043 })
5044 }
5045}
5046
5047impl EventEmitter<Event> for Project {}
5048
5049impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5050 fn from(val: &'a ProjectPath) -> Self {
5051 SettingsLocation {
5052 worktree_id: val.worktree_id,
5053 path: val.path.as_ref(),
5054 }
5055 }
5056}
5057
5058impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
5059 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5060 Self {
5061 worktree_id,
5062 path: path.as_ref().into(),
5063 }
5064 }
5065}
5066
5067pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
5068 let mut path_components = path.components();
5069 let mut base_components = base.components();
5070 let mut components: Vec<Component> = Vec::new();
5071 loop {
5072 match (path_components.next(), base_components.next()) {
5073 (None, None) => break,
5074 (Some(a), None) => {
5075 components.push(a);
5076 components.extend(path_components.by_ref());
5077 break;
5078 }
5079 (None, _) => components.push(Component::ParentDir),
5080 (Some(a), Some(b)) if components.is_empty() && a == b => (),
5081 (Some(a), Some(Component::CurDir)) => components.push(a),
5082 (Some(a), Some(_)) => {
5083 components.push(Component::ParentDir);
5084 for _ in base_components {
5085 components.push(Component::ParentDir);
5086 }
5087 components.push(a);
5088 components.extend(path_components.by_ref());
5089 break;
5090 }
5091 }
5092 }
5093 components.iter().map(|c| c.as_os_str()).collect()
5094}
5095
5096fn resolve_path(base: &Path, path: &Path) -> PathBuf {
5097 let mut result = base.to_path_buf();
5098 for component in path.components() {
5099 match component {
5100 Component::ParentDir => {
5101 result.pop();
5102 }
5103 Component::CurDir => (),
5104 _ => result.push(component),
5105 }
5106 }
5107 result
5108}
5109
5110/// ResolvedPath is a path that has been resolved to either a ProjectPath
5111/// or an AbsPath and that *exists*.
5112#[derive(Debug, Clone)]
5113pub enum ResolvedPath {
5114 ProjectPath {
5115 project_path: ProjectPath,
5116 is_dir: bool,
5117 },
5118 AbsPath {
5119 path: PathBuf,
5120 is_dir: bool,
5121 },
5122}
5123
5124impl ResolvedPath {
5125 pub fn abs_path(&self) -> Option<&Path> {
5126 match self {
5127 Self::AbsPath { path, .. } => Some(path.as_path()),
5128 _ => None,
5129 }
5130 }
5131
5132 pub fn into_abs_path(self) -> Option<PathBuf> {
5133 match self {
5134 Self::AbsPath { path, .. } => Some(path),
5135 _ => None,
5136 }
5137 }
5138
5139 pub fn project_path(&self) -> Option<&ProjectPath> {
5140 match self {
5141 Self::ProjectPath { project_path, .. } => Some(&project_path),
5142 _ => None,
5143 }
5144 }
5145
5146 pub fn is_file(&self) -> bool {
5147 !self.is_dir()
5148 }
5149
5150 pub fn is_dir(&self) -> bool {
5151 match self {
5152 Self::ProjectPath { is_dir, .. } => *is_dir,
5153 Self::AbsPath { is_dir, .. } => *is_dir,
5154 }
5155 }
5156}
5157
5158impl ProjectItem for Buffer {
5159 fn try_open(
5160 project: &Entity<Project>,
5161 path: &ProjectPath,
5162 cx: &mut App,
5163 ) -> Option<Task<Result<Entity<Self>>>> {
5164 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5165 }
5166
5167 fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
5168 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
5169 }
5170
5171 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5172 self.file().map(|file| ProjectPath {
5173 worktree_id: file.worktree_id(cx),
5174 path: file.path().clone(),
5175 })
5176 }
5177
5178 fn is_dirty(&self) -> bool {
5179 self.is_dirty()
5180 }
5181}
5182
5183impl Completion {
5184 pub fn kind(&self) -> Option<CompletionItemKind> {
5185 self.source
5186 // `lsp::CompletionListItemDefaults` has no `kind` field
5187 .lsp_completion(false)
5188 .and_then(|lsp_completion| lsp_completion.kind)
5189 }
5190
5191 pub fn label(&self) -> Option<String> {
5192 self.source
5193 .lsp_completion(false)
5194 .map(|lsp_completion| lsp_completion.label.clone())
5195 }
5196
5197 /// A key that can be used to sort completions when displaying
5198 /// them to the user.
5199 pub fn sort_key(&self) -> (usize, &str) {
5200 const DEFAULT_KIND_KEY: usize = 3;
5201 let kind_key = self
5202 .kind()
5203 .and_then(|lsp_completion_kind| match lsp_completion_kind {
5204 lsp::CompletionItemKind::KEYWORD => Some(0),
5205 lsp::CompletionItemKind::VARIABLE => Some(1),
5206 lsp::CompletionItemKind::CONSTANT => Some(2),
5207 _ => None,
5208 })
5209 .unwrap_or(DEFAULT_KIND_KEY);
5210 (kind_key, &self.label.text[self.label.filter_range.clone()])
5211 }
5212
5213 /// Whether this completion is a snippet.
5214 pub fn is_snippet(&self) -> bool {
5215 self.source
5216 // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5217 .lsp_completion(true)
5218 .map_or(false, |lsp_completion| {
5219 lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5220 })
5221 }
5222
5223 /// Returns the corresponding color for this completion.
5224 ///
5225 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5226 pub fn color(&self) -> Option<Hsla> {
5227 // `lsp::CompletionListItemDefaults` has no `kind` field
5228 let lsp_completion = self.source.lsp_completion(false)?;
5229 if lsp_completion.kind? == CompletionItemKind::COLOR {
5230 return color_extractor::extract_color(&lsp_completion);
5231 }
5232 None
5233 }
5234}
5235
5236pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
5237 entries.sort_by(|entry_a, entry_b| {
5238 let entry_a = entry_a.as_ref();
5239 let entry_b = entry_b.as_ref();
5240 compare_paths(
5241 (&entry_a.path, entry_a.is_file()),
5242 (&entry_b.path, entry_b.is_file()),
5243 )
5244 });
5245}
5246
5247fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5248 match level {
5249 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5250 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5251 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5252 }
5253}