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