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