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