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