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