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