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