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