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