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