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