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