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