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