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