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;
29use encoding_rs::Encoding;
30pub use environment::ProjectEnvironmentEvent;
31use git::repository::get_git_committer;
32use git_store::{Repository, RepositoryId};
33pub mod search_history;
34mod yarn;
35
36use dap::inline_value::{InlineValueLocation, VariableLookupKind, VariableScope};
37use task::Shell;
38
39use crate::{
40 agent_server_store::AllAgentServersSettings,
41 git_store::GitStore,
42 lsp_store::{SymbolLocation, log_store::LogKind},
43};
44pub use agent_server_store::{AgentServerStore, AgentServersUpdated, ExternalAgentServerName};
45pub use git_store::{
46 ConflictRegion, ConflictSet, ConflictSetSnapshot, ConflictSetUpdate,
47 git_traversal::{ChildEntriesGitIter, GitEntry, GitEntryRef, GitTraversal},
48};
49pub use manifest_tree::ManifestTree;
50
51use anyhow::{Context as _, Result, anyhow};
52use buffer_store::{BufferStore, BufferStoreEvent};
53use client::{Client, Collaborator, PendingEntitySubscription, TypedEnvelope, UserStore, proto};
54use clock::ReplicaId;
55
56use dap::client::DebugAdapterClient;
57
58use collections::{BTreeSet, HashMap, HashSet, IndexSet};
59use debounced_delay::DebouncedDelay;
60pub use debugger::breakpoint_store::BreakpointWithPosition;
61use debugger::{
62 breakpoint_store::{ActiveStackFrame, BreakpointStore},
63 dap_store::{DapStore, DapStoreEvent},
64 session::Session,
65};
66pub use environment::ProjectEnvironment;
67#[cfg(test)]
68use futures::future::join_all;
69use futures::{
70 StreamExt,
71 channel::mpsc::{self, UnboundedReceiver},
72 future::{Shared, try_join_all},
73};
74pub use image_store::{ImageItem, ImageStore};
75use image_store::{ImageItemEvent, ImageStoreEvent};
76
77use ::git::{blame::Blame, status::FileStatus};
78use gpui::{
79 App, AppContext, AsyncApp, BorrowAppContext, Context, Entity, EventEmitter, Hsla, SharedString,
80 Task, WeakEntity, Window,
81};
82use language::{
83 Buffer, BufferEvent, Capability, CodeLabel, CursorShape, Language, LanguageName,
84 LanguageRegistry, PointUtf16, ToOffset, ToPointUtf16, Toolchain, ToolchainMetadata,
85 ToolchainScope, Transaction, Unclipped, language_settings::InlayHintKind,
86 proto::split_operations,
87};
88use lsp::{
89 CodeActionKind, CompletionContext, CompletionItemKind, DocumentHighlightKind, InsertTextMode,
90 LanguageServerId, LanguageServerName, LanguageServerSelector, MessageActionItem,
91};
92use lsp_command::*;
93use lsp_store::{CompletionDocumentation, LspFormatTarget, OpenLspBufferHandle};
94pub use manifest_tree::ManifestProvidersStore;
95use node_runtime::NodeRuntime;
96use parking_lot::Mutex;
97pub use prettier_store::PrettierStore;
98use project_settings::{ProjectSettings, SettingsObserver, SettingsObserverEvent};
99use remote::{RemoteClient, RemoteConnectionOptions};
100use rpc::{
101 AnyProtoClient, ErrorCode,
102 proto::{LanguageServerPromptResponse, REMOTE_SERVER_PROJECT_ID},
103};
104use search::{SearchInputKind, SearchQuery, SearchResult};
105use search_history::SearchHistory;
106use settings::{InvalidSettingsError, Settings, SettingsLocation, SettingsStore};
107use smol::channel::Receiver;
108use snippet::Snippet;
109use snippet_provider::SnippetProvider;
110use std::{
111 borrow::Cow,
112 collections::BTreeMap,
113 ops::Range,
114 path::{Path, PathBuf},
115 pin::pin,
116 str,
117 sync::Arc,
118 time::Duration,
119};
120
121use task_store::TaskStore;
122use terminals::Terminals;
123use text::{Anchor, BufferId, OffsetRangeExt, Point, Rope};
124use toolchain_store::EmptyToolchainStore;
125use util::{
126 ResultExt as _, maybe,
127 paths::{PathStyle, SanitizedPath, compare_paths, is_absolute},
128 rel_path::RelPath,
129};
130use worktree::{CreatedEntry, Snapshot, Traversal};
131pub use worktree::{
132 Entry, EntryKind, FS_WATCH_LATENCY, File, LocalWorktree, PathChange, ProjectEntryId,
133 UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
134};
135use worktree_store::{WorktreeStore, WorktreeStoreEvent};
136
137pub use fs::*;
138pub use language::Location;
139#[cfg(any(test, feature = "test-support"))]
140pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
141pub use task_inventory::{
142 BasicContextProvider, ContextProviderWithTasks, DebugScenarioContext, Inventory, TaskContexts,
143 TaskSourceKind,
144};
145
146pub use buffer_store::ProjectTransaction;
147pub use lsp_store::{
148 DiagnosticSummary, InvalidationStrategy, LanguageServerLogType, LanguageServerProgress,
149 LanguageServerPromptRequest, LanguageServerStatus, LanguageServerToQuery, LspStore,
150 LspStoreEvent, ProgressToken, SERVER_PROGRESS_THROTTLE_TIMEOUT,
151};
152pub use toolchain_store::{ToolchainStore, Toolchains};
153const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
154const MAX_SEARCH_RESULT_FILES: usize = 5_000;
155const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
156
157pub trait ProjectItem: 'static {
158 fn try_open(
159 project: &Entity<Project>,
160 path: &ProjectPath,
161 cx: &mut App,
162 ) -> Option<Task<Result<Entity<Self>>>>
163 where
164 Self: Sized;
165 fn entry_id(&self, cx: &App) -> Option<ProjectEntryId>;
166 fn project_path(&self, cx: &App) -> Option<ProjectPath>;
167 fn is_dirty(&self) -> bool;
168}
169
170#[derive(Clone)]
171pub enum OpenedBufferEvent {
172 Disconnected,
173 Ok(BufferId),
174 Err(BufferId, Arc<anyhow::Error>),
175}
176
177/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
178/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
179/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
180///
181/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
182pub struct Project {
183 active_entry: Option<ProjectEntryId>,
184 buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
185 languages: Arc<LanguageRegistry>,
186 dap_store: Entity<DapStore>,
187 agent_server_store: Entity<AgentServerStore>,
188
189 breakpoint_store: Entity<BreakpointStore>,
190 collab_client: Arc<client::Client>,
191 join_project_response_message_id: u32,
192 task_store: Entity<TaskStore>,
193 user_store: Entity<UserStore>,
194 fs: Arc<dyn Fs>,
195 remote_client: Option<Entity<RemoteClient>>,
196 client_state: ProjectClientState,
197 git_store: Entity<GitStore>,
198 collaborators: HashMap<proto::PeerId, Collaborator>,
199 client_subscriptions: Vec<client::Subscription>,
200 worktree_store: Entity<WorktreeStore>,
201 buffer_store: Entity<BufferStore>,
202 context_server_store: Entity<ContextServerStore>,
203 image_store: Entity<ImageStore>,
204 lsp_store: Entity<LspStore>,
205 _subscriptions: Vec<gpui::Subscription>,
206 buffers_needing_diff: HashSet<WeakEntity<Buffer>>,
207 git_diff_debouncer: DebouncedDelay<Self>,
208 remotely_created_models: Arc<Mutex<RemotelyCreatedModels>>,
209 terminals: Terminals,
210 node: Option<NodeRuntime>,
211 search_history: SearchHistory,
212 search_included_history: SearchHistory,
213 search_excluded_history: SearchHistory,
214 snippets: Entity<SnippetProvider>,
215 environment: Entity<ProjectEnvironment>,
216 settings_observer: Entity<SettingsObserver>,
217 toolchain_store: Option<Entity<ToolchainStore>>,
218 agent_location: Option<AgentLocation>,
219 pub encoding: Arc<std::sync::Mutex<&'static Encoding>>,
220}
221
222#[derive(Clone, Debug, PartialEq, Eq)]
223pub struct AgentLocation {
224 pub buffer: WeakEntity<Buffer>,
225 pub position: Anchor,
226}
227
228#[derive(Default)]
229struct RemotelyCreatedModels {
230 worktrees: Vec<Entity<Worktree>>,
231 buffers: Vec<Entity<Buffer>>,
232 retain_count: usize,
233}
234
235struct RemotelyCreatedModelGuard {
236 remote_models: std::sync::Weak<Mutex<RemotelyCreatedModels>>,
237}
238
239impl Drop for RemotelyCreatedModelGuard {
240 fn drop(&mut self) {
241 if let Some(remote_models) = self.remote_models.upgrade() {
242 let mut remote_models = remote_models.lock();
243 assert!(
244 remote_models.retain_count > 0,
245 "RemotelyCreatedModelGuard dropped too many times"
246 );
247 remote_models.retain_count -= 1;
248 if remote_models.retain_count == 0 {
249 remote_models.buffers.clear();
250 remote_models.worktrees.clear();
251 }
252 }
253 }
254}
255/// Message ordered with respect to buffer operations
256#[derive(Debug)]
257enum BufferOrderedMessage {
258 Operation {
259 buffer_id: BufferId,
260 operation: proto::Operation,
261 },
262 LanguageServerUpdate {
263 language_server_id: LanguageServerId,
264 message: proto::update_language_server::Variant,
265 name: Option<LanguageServerName>,
266 },
267 Resync,
268}
269
270#[derive(Debug)]
271enum ProjectClientState {
272 /// Single-player mode.
273 Local,
274 /// Multi-player mode but still a local project.
275 Shared { remote_id: u64 },
276 /// Multi-player mode but working on a remote project.
277 Remote {
278 sharing_has_stopped: bool,
279 capability: Capability,
280 remote_id: u64,
281 replica_id: ReplicaId,
282 },
283}
284
285#[derive(Clone, Debug, PartialEq)]
286pub enum Event {
287 LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
288 LanguageServerRemoved(LanguageServerId),
289 LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
290 // [`lsp::notification::DidOpenTextDocument`] was sent to this server using the buffer data.
291 // Zed's buffer-related data is updated accordingly.
292 LanguageServerBufferRegistered {
293 server_id: LanguageServerId,
294 buffer_id: BufferId,
295 buffer_abs_path: PathBuf,
296 name: Option<LanguageServerName>,
297 },
298 ToggleLspLogs {
299 server_id: LanguageServerId,
300 enabled: bool,
301 toggled_log_kind: LogKind,
302 },
303 Toast {
304 notification_id: SharedString,
305 message: String,
306 },
307 HideToast {
308 notification_id: SharedString,
309 },
310 LanguageServerPrompt(LanguageServerPromptRequest),
311 LanguageNotFound(Entity<Buffer>),
312 ActiveEntryChanged(Option<ProjectEntryId>),
313 ActivateProjectPanel,
314 WorktreeAdded(WorktreeId),
315 WorktreeOrderChanged,
316 WorktreeRemoved(WorktreeId),
317 WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
318 DiskBasedDiagnosticsStarted {
319 language_server_id: LanguageServerId,
320 },
321 DiskBasedDiagnosticsFinished {
322 language_server_id: LanguageServerId,
323 },
324 DiagnosticsUpdated {
325 paths: Vec<ProjectPath>,
326 language_server_id: LanguageServerId,
327 },
328 RemoteIdChanged(Option<u64>),
329 DisconnectedFromHost,
330 DisconnectedFromSshRemote,
331 Closed,
332 DeletedEntry(WorktreeId, ProjectEntryId),
333 CollaboratorUpdated {
334 old_peer_id: proto::PeerId,
335 new_peer_id: proto::PeerId,
336 },
337 CollaboratorJoined(proto::PeerId),
338 CollaboratorLeft(proto::PeerId),
339 HostReshared,
340 Reshared,
341 Rejoined,
342 RefreshInlayHints(LanguageServerId),
343 RefreshCodeLens,
344 RevealInProjectPanel(ProjectEntryId),
345 SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
346 ExpandedAllForEntry(WorktreeId, ProjectEntryId),
347 EntryRenamed(ProjectTransaction),
348 AgentLocationChanged,
349}
350
351pub struct AgentLocationChanged;
352
353pub enum DebugAdapterClientState {
354 Starting(Task<Option<Arc<DebugAdapterClient>>>),
355 Running(Arc<DebugAdapterClient>),
356}
357
358#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
359pub struct ProjectPath {
360 pub worktree_id: WorktreeId,
361 pub path: Arc<RelPath>,
362}
363
364impl ProjectPath {
365 pub fn from_file(value: &dyn language::File, cx: &App) -> Self {
366 ProjectPath {
367 worktree_id: value.worktree_id(cx),
368 path: value.path().clone(),
369 }
370 }
371
372 pub fn from_proto(p: proto::ProjectPath) -> Option<Self> {
373 Some(Self {
374 worktree_id: WorktreeId::from_proto(p.worktree_id),
375 path: RelPath::from_proto(&p.path).log_err()?,
376 })
377 }
378
379 pub fn to_proto(&self) -> proto::ProjectPath {
380 proto::ProjectPath {
381 worktree_id: self.worktree_id.to_proto(),
382 path: self.path.as_ref().to_proto(),
383 }
384 }
385
386 pub fn root_path(worktree_id: WorktreeId) -> Self {
387 Self {
388 worktree_id,
389 path: RelPath::empty().into(),
390 }
391 }
392
393 pub fn starts_with(&self, other: &ProjectPath) -> bool {
394 self.worktree_id == other.worktree_id && self.path.starts_with(&other.path)
395 }
396}
397
398#[derive(Debug, Default)]
399pub enum PrepareRenameResponse {
400 Success(Range<Anchor>),
401 OnlyUnpreparedRenameSupported,
402 #[default]
403 InvalidPosition,
404}
405
406#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
407pub enum InlayId {
408 EditPrediction(usize),
409 DebuggerValue(usize),
410 // LSP
411 Hint(usize),
412 Color(usize),
413}
414
415impl InlayId {
416 pub fn id(&self) -> usize {
417 match self {
418 Self::EditPrediction(id) => *id,
419 Self::DebuggerValue(id) => *id,
420 Self::Hint(id) => *id,
421 Self::Color(id) => *id,
422 }
423 }
424}
425
426#[derive(Debug, Clone, PartialEq, Eq)]
427pub struct InlayHint {
428 pub position: language::Anchor,
429 pub label: InlayHintLabel,
430 pub kind: Option<InlayHintKind>,
431 pub padding_left: bool,
432 pub padding_right: bool,
433 pub tooltip: Option<InlayHintTooltip>,
434 pub resolve_state: ResolveState,
435}
436
437/// The user's intent behind a given completion confirmation
438#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
439pub enum CompletionIntent {
440 /// The user intends to 'commit' this result, if possible
441 /// completion confirmations should run side effects.
442 ///
443 /// For LSP completions, will respect the setting `completions.lsp_insert_mode`.
444 Complete,
445 /// Similar to [Self::Complete], but behaves like `lsp_insert_mode` is set to `insert`.
446 CompleteWithInsert,
447 /// Similar to [Self::Complete], but behaves like `lsp_insert_mode` is set to `replace`.
448 CompleteWithReplace,
449 /// The user intends to continue 'composing' this completion
450 /// completion confirmations should not run side effects and
451 /// let the user continue composing their action
452 Compose,
453}
454
455impl CompletionIntent {
456 pub fn is_complete(&self) -> bool {
457 self == &Self::Complete
458 }
459
460 pub fn is_compose(&self) -> bool {
461 self == &Self::Compose
462 }
463}
464
465/// Similar to `CoreCompletion`, but with extra metadata attached.
466#[derive(Clone)]
467pub struct Completion {
468 /// The range of text that will be replaced by this completion.
469 pub replace_range: Range<Anchor>,
470 /// The new text that will be inserted.
471 pub new_text: String,
472 /// A label for this completion that is shown in the menu.
473 pub label: CodeLabel,
474 /// The documentation for this completion.
475 pub documentation: Option<CompletionDocumentation>,
476 /// Completion data source which it was constructed from.
477 pub source: CompletionSource,
478 /// A path to an icon for this completion that is shown in the menu.
479 pub icon_path: Option<SharedString>,
480 /// Whether to adjust indentation (the default) or not.
481 pub insert_text_mode: Option<InsertTextMode>,
482 /// An optional callback to invoke when this completion is confirmed.
483 /// Returns, whether new completions should be retriggered after the current one.
484 /// If `true` is returned, the editor will show a new completion menu after this completion is confirmed.
485 /// if no confirmation is provided or `false` is returned, the completion will be committed.
486 pub confirm: Option<Arc<dyn Send + Sync + Fn(CompletionIntent, &mut Window, &mut App) -> bool>>,
487}
488
489#[derive(Debug, Clone)]
490pub enum CompletionSource {
491 Lsp {
492 /// The alternate `insert` range, if provided by the LSP server.
493 insert_range: Option<Range<Anchor>>,
494 /// The id of the language server that produced this completion.
495 server_id: LanguageServerId,
496 /// The raw completion provided by the language server.
497 lsp_completion: Box<lsp::CompletionItem>,
498 /// A set of defaults for this completion item.
499 lsp_defaults: Option<Arc<lsp::CompletionListItemDefaults>>,
500 /// Whether this completion has been resolved, to ensure it happens once per completion.
501 resolved: bool,
502 },
503 Dap {
504 /// The sort text for this completion.
505 sort_text: String,
506 },
507 Custom,
508 BufferWord {
509 word_range: Range<Anchor>,
510 resolved: bool,
511 },
512}
513
514impl CompletionSource {
515 pub fn server_id(&self) -> Option<LanguageServerId> {
516 if let CompletionSource::Lsp { server_id, .. } = self {
517 Some(*server_id)
518 } else {
519 None
520 }
521 }
522
523 pub fn lsp_completion(&self, apply_defaults: bool) -> Option<Cow<'_, lsp::CompletionItem>> {
524 if let Self::Lsp {
525 lsp_completion,
526 lsp_defaults,
527 ..
528 } = self
529 {
530 if apply_defaults && let Some(lsp_defaults) = lsp_defaults {
531 let mut completion_with_defaults = *lsp_completion.clone();
532 let default_commit_characters = lsp_defaults.commit_characters.as_ref();
533 let default_edit_range = lsp_defaults.edit_range.as_ref();
534 let default_insert_text_format = lsp_defaults.insert_text_format.as_ref();
535 let default_insert_text_mode = lsp_defaults.insert_text_mode.as_ref();
536
537 if default_commit_characters.is_some()
538 || default_edit_range.is_some()
539 || default_insert_text_format.is_some()
540 || default_insert_text_mode.is_some()
541 {
542 if completion_with_defaults.commit_characters.is_none()
543 && default_commit_characters.is_some()
544 {
545 completion_with_defaults.commit_characters =
546 default_commit_characters.cloned()
547 }
548 if completion_with_defaults.text_edit.is_none() {
549 match default_edit_range {
550 Some(lsp::CompletionListItemDefaultsEditRange::Range(range)) => {
551 completion_with_defaults.text_edit =
552 Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
553 range: *range,
554 new_text: completion_with_defaults.label.clone(),
555 }))
556 }
557 Some(lsp::CompletionListItemDefaultsEditRange::InsertAndReplace {
558 insert,
559 replace,
560 }) => {
561 completion_with_defaults.text_edit =
562 Some(lsp::CompletionTextEdit::InsertAndReplace(
563 lsp::InsertReplaceEdit {
564 new_text: completion_with_defaults.label.clone(),
565 insert: *insert,
566 replace: *replace,
567 },
568 ))
569 }
570 None => {}
571 }
572 }
573 if completion_with_defaults.insert_text_format.is_none()
574 && default_insert_text_format.is_some()
575 {
576 completion_with_defaults.insert_text_format =
577 default_insert_text_format.cloned()
578 }
579 if completion_with_defaults.insert_text_mode.is_none()
580 && default_insert_text_mode.is_some()
581 {
582 completion_with_defaults.insert_text_mode =
583 default_insert_text_mode.cloned()
584 }
585 }
586 return Some(Cow::Owned(completion_with_defaults));
587 }
588 Some(Cow::Borrowed(lsp_completion))
589 } else {
590 None
591 }
592 }
593}
594
595impl std::fmt::Debug for Completion {
596 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
597 f.debug_struct("Completion")
598 .field("replace_range", &self.replace_range)
599 .field("new_text", &self.new_text)
600 .field("label", &self.label)
601 .field("documentation", &self.documentation)
602 .field("source", &self.source)
603 .finish()
604 }
605}
606
607/// Response from a source of completions.
608pub struct CompletionResponse {
609 pub completions: Vec<Completion>,
610 pub display_options: CompletionDisplayOptions,
611 /// When false, indicates that the list is complete and so does not need to be re-queried if it
612 /// can be filtered instead.
613 pub is_incomplete: bool,
614}
615
616#[derive(Default)]
617pub struct CompletionDisplayOptions {
618 pub dynamic_width: bool,
619}
620
621impl CompletionDisplayOptions {
622 pub fn merge(&mut self, other: &CompletionDisplayOptions) {
623 self.dynamic_width = self.dynamic_width && other.dynamic_width;
624 }
625}
626
627/// Response from language server completion request.
628#[derive(Clone, Debug, Default)]
629pub(crate) struct CoreCompletionResponse {
630 pub completions: Vec<CoreCompletion>,
631 /// When false, indicates that the list is complete and so does not need to be re-queried if it
632 /// can be filtered instead.
633 pub is_incomplete: bool,
634}
635
636/// A generic completion that can come from different sources.
637#[derive(Clone, Debug)]
638pub(crate) struct CoreCompletion {
639 replace_range: Range<Anchor>,
640 new_text: String,
641 source: CompletionSource,
642}
643
644/// A code action provided by a language server.
645#[derive(Clone, Debug, PartialEq)]
646pub struct CodeAction {
647 /// The id of the language server that produced this code action.
648 pub server_id: LanguageServerId,
649 /// The range of the buffer where this code action is applicable.
650 pub range: Range<Anchor>,
651 /// The raw code action provided by the language server.
652 /// Can be either an action or a command.
653 pub lsp_action: LspAction,
654 /// Whether the action needs to be resolved using the language server.
655 pub resolved: bool,
656}
657
658/// An action sent back by a language server.
659#[derive(Clone, Debug, PartialEq)]
660pub enum LspAction {
661 /// An action with the full data, may have a command or may not.
662 /// May require resolving.
663 Action(Box<lsp::CodeAction>),
664 /// A command data to run as an action.
665 Command(lsp::Command),
666 /// A code lens data to run as an action.
667 CodeLens(lsp::CodeLens),
668}
669
670impl LspAction {
671 pub fn title(&self) -> &str {
672 match self {
673 Self::Action(action) => &action.title,
674 Self::Command(command) => &command.title,
675 Self::CodeLens(lens) => lens
676 .command
677 .as_ref()
678 .map(|command| command.title.as_str())
679 .unwrap_or("Unknown command"),
680 }
681 }
682
683 fn action_kind(&self) -> Option<lsp::CodeActionKind> {
684 match self {
685 Self::Action(action) => action.kind.clone(),
686 Self::Command(_) => Some(lsp::CodeActionKind::new("command")),
687 Self::CodeLens(_) => Some(lsp::CodeActionKind::new("code lens")),
688 }
689 }
690
691 fn edit(&self) -> Option<&lsp::WorkspaceEdit> {
692 match self {
693 Self::Action(action) => action.edit.as_ref(),
694 Self::Command(_) => None,
695 Self::CodeLens(_) => None,
696 }
697 }
698
699 fn command(&self) -> Option<&lsp::Command> {
700 match self {
701 Self::Action(action) => action.command.as_ref(),
702 Self::Command(command) => Some(command),
703 Self::CodeLens(lens) => lens.command.as_ref(),
704 }
705 }
706}
707
708#[derive(Debug, Clone, PartialEq, Eq)]
709pub enum ResolveState {
710 Resolved,
711 CanResolve(LanguageServerId, Option<lsp::LSPAny>),
712 Resolving,
713}
714impl InlayHint {
715 pub fn text(&self) -> Rope {
716 match &self.label {
717 InlayHintLabel::String(s) => Rope::from_str_small(s),
718 InlayHintLabel::LabelParts(parts) => {
719 Rope::from_iter_small(parts.iter().map(|part| &*part.value))
720 }
721 }
722 }
723}
724
725#[derive(Debug, Clone, PartialEq, Eq)]
726pub enum InlayHintLabel {
727 String(String),
728 LabelParts(Vec<InlayHintLabelPart>),
729}
730
731#[derive(Debug, Clone, PartialEq, Eq)]
732pub struct InlayHintLabelPart {
733 pub value: String,
734 pub tooltip: Option<InlayHintLabelPartTooltip>,
735 pub location: Option<(LanguageServerId, lsp::Location)>,
736}
737
738#[derive(Debug, Clone, PartialEq, Eq)]
739pub enum InlayHintTooltip {
740 String(String),
741 MarkupContent(MarkupContent),
742}
743
744#[derive(Debug, Clone, PartialEq, Eq)]
745pub enum InlayHintLabelPartTooltip {
746 String(String),
747 MarkupContent(MarkupContent),
748}
749
750#[derive(Debug, Clone, PartialEq, Eq)]
751pub struct MarkupContent {
752 pub kind: HoverBlockKind,
753 pub value: String,
754}
755
756#[derive(Debug, Clone, PartialEq)]
757pub struct LocationLink {
758 pub origin: Option<Location>,
759 pub target: Location,
760}
761
762#[derive(Debug)]
763pub struct DocumentHighlight {
764 pub range: Range<language::Anchor>,
765 pub kind: DocumentHighlightKind,
766}
767
768#[derive(Clone, Debug)]
769pub struct Symbol {
770 pub language_server_name: LanguageServerName,
771 pub source_worktree_id: WorktreeId,
772 pub source_language_server_id: LanguageServerId,
773 pub path: SymbolLocation,
774 pub label: CodeLabel,
775 pub name: String,
776 pub kind: lsp::SymbolKind,
777 pub range: Range<Unclipped<PointUtf16>>,
778}
779
780#[derive(Clone, Debug)]
781pub struct DocumentSymbol {
782 pub name: String,
783 pub kind: lsp::SymbolKind,
784 pub range: Range<Unclipped<PointUtf16>>,
785 pub selection_range: Range<Unclipped<PointUtf16>>,
786 pub children: Vec<DocumentSymbol>,
787}
788
789#[derive(Clone, Debug, PartialEq)]
790pub struct HoverBlock {
791 pub text: String,
792 pub kind: HoverBlockKind,
793}
794
795#[derive(Clone, Debug, PartialEq, Eq)]
796pub enum HoverBlockKind {
797 PlainText,
798 Markdown,
799 Code { language: String },
800}
801
802#[derive(Debug, Clone)]
803pub struct Hover {
804 pub contents: Vec<HoverBlock>,
805 pub range: Option<Range<language::Anchor>>,
806 pub language: Option<Arc<Language>>,
807}
808
809impl Hover {
810 pub fn is_empty(&self) -> bool {
811 self.contents.iter().all(|block| block.text.is_empty())
812 }
813}
814
815enum EntitySubscription {
816 Project(PendingEntitySubscription<Project>),
817 BufferStore(PendingEntitySubscription<BufferStore>),
818 GitStore(PendingEntitySubscription<GitStore>),
819 WorktreeStore(PendingEntitySubscription<WorktreeStore>),
820 LspStore(PendingEntitySubscription<LspStore>),
821 SettingsObserver(PendingEntitySubscription<SettingsObserver>),
822 DapStore(PendingEntitySubscription<DapStore>),
823}
824
825#[derive(Debug, Clone)]
826pub struct DirectoryItem {
827 pub path: PathBuf,
828 pub is_dir: bool,
829}
830
831#[derive(Clone, Debug, PartialEq)]
832pub struct DocumentColor {
833 pub lsp_range: lsp::Range,
834 pub color: lsp::Color,
835 pub resolved: bool,
836 pub color_presentations: Vec<ColorPresentation>,
837}
838
839impl Eq for DocumentColor {}
840
841impl std::hash::Hash for DocumentColor {
842 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
843 self.lsp_range.hash(state);
844 self.color.red.to_bits().hash(state);
845 self.color.green.to_bits().hash(state);
846 self.color.blue.to_bits().hash(state);
847 self.color.alpha.to_bits().hash(state);
848 self.resolved.hash(state);
849 self.color_presentations.hash(state);
850 }
851}
852
853#[derive(Clone, Debug, PartialEq, Eq)]
854pub struct ColorPresentation {
855 pub label: SharedString,
856 pub text_edit: Option<lsp::TextEdit>,
857 pub additional_text_edits: Vec<lsp::TextEdit>,
858}
859
860impl std::hash::Hash for ColorPresentation {
861 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
862 self.label.hash(state);
863 if let Some(ref edit) = self.text_edit {
864 edit.range.hash(state);
865 edit.new_text.hash(state);
866 }
867 self.additional_text_edits.len().hash(state);
868 for edit in &self.additional_text_edits {
869 edit.range.hash(state);
870 edit.new_text.hash(state);
871 }
872 }
873}
874
875#[derive(Clone)]
876pub enum DirectoryLister {
877 Project(Entity<Project>),
878 Local(Entity<Project>, Arc<dyn Fs>),
879}
880
881impl std::fmt::Debug for DirectoryLister {
882 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
883 match self {
884 DirectoryLister::Project(project) => {
885 write!(f, "DirectoryLister::Project({project:?})")
886 }
887 DirectoryLister::Local(project, _) => {
888 write!(f, "DirectoryLister::Local({project:?})")
889 }
890 }
891 }
892}
893
894impl DirectoryLister {
895 pub fn is_local(&self, cx: &App) -> bool {
896 match self {
897 DirectoryLister::Local(..) => true,
898 DirectoryLister::Project(project) => project.read(cx).is_local(),
899 }
900 }
901
902 pub fn resolve_tilde<'a>(&self, path: &'a String, cx: &App) -> Cow<'a, str> {
903 if self.is_local(cx) {
904 shellexpand::tilde(path)
905 } else {
906 Cow::from(path)
907 }
908 }
909
910 pub fn default_query(&self, cx: &mut App) -> String {
911 let project = match self {
912 DirectoryLister::Project(project) => project,
913 DirectoryLister::Local(project, _) => project,
914 }
915 .read(cx);
916 let path_style = project.path_style(cx);
917 project
918 .visible_worktrees(cx)
919 .next()
920 .map(|worktree| worktree.read(cx).abs_path().to_string_lossy().into_owned())
921 .or_else(|| std::env::home_dir().map(|dir| dir.to_string_lossy().into_owned()))
922 .map(|mut s| {
923 s.push_str(path_style.separator());
924 s
925 })
926 .unwrap_or_else(|| {
927 if path_style.is_windows() {
928 "C:\\"
929 } else {
930 "~/"
931 }
932 .to_string()
933 })
934 }
935
936 pub fn list_directory(&self, path: String, cx: &mut App) -> Task<Result<Vec<DirectoryItem>>> {
937 match self {
938 DirectoryLister::Project(project) => {
939 project.update(cx, |project, cx| project.list_directory(path, cx))
940 }
941 DirectoryLister::Local(_, fs) => {
942 let fs = fs.clone();
943 cx.background_spawn(async move {
944 let mut results = vec![];
945 let expanded = shellexpand::tilde(&path);
946 let query = Path::new(expanded.as_ref());
947 let mut response = fs.read_dir(query).await?;
948 while let Some(path) = response.next().await {
949 let path = path?;
950 if let Some(file_name) = path.file_name() {
951 results.push(DirectoryItem {
952 path: PathBuf::from(file_name.to_os_string()),
953 is_dir: fs.is_dir(&path).await,
954 });
955 }
956 }
957 Ok(results)
958 })
959 }
960 }
961 }
962}
963
964#[cfg(any(test, feature = "test-support"))]
965pub const DEFAULT_COMPLETION_CONTEXT: CompletionContext = CompletionContext {
966 trigger_kind: lsp::CompletionTriggerKind::INVOKED,
967 trigger_character: None,
968};
969
970/// An LSP diagnostics associated with a certain language server.
971#[derive(Clone, Debug, Default)]
972pub enum LspPullDiagnostics {
973 #[default]
974 Default,
975 Response {
976 /// The id of the language server that produced diagnostics.
977 server_id: LanguageServerId,
978 /// URI of the resource,
979 uri: lsp::Uri,
980 /// The diagnostics produced by this language server.
981 diagnostics: PulledDiagnostics,
982 },
983}
984
985#[derive(Clone, Debug)]
986pub enum PulledDiagnostics {
987 Unchanged {
988 /// An ID the current pulled batch for this file.
989 /// If given, can be used to query workspace diagnostics partially.
990 result_id: String,
991 },
992 Changed {
993 result_id: Option<String>,
994 diagnostics: Vec<lsp::Diagnostic>,
995 },
996}
997
998/// Whether to disable all AI features in Zed.
999///
1000/// Default: false
1001#[derive(Copy, Clone, Debug)]
1002pub struct DisableAiSettings {
1003 pub disable_ai: bool,
1004}
1005
1006impl settings::Settings for DisableAiSettings {
1007 fn from_settings(content: &settings::SettingsContent) -> Self {
1008 Self {
1009 disable_ai: content.disable_ai.unwrap().0,
1010 }
1011 }
1012}
1013
1014impl Project {
1015 pub fn init_settings(cx: &mut App) {
1016 WorktreeSettings::register(cx);
1017 ProjectSettings::register(cx);
1018 DisableAiSettings::register(cx);
1019 AllAgentServersSettings::register(cx);
1020 }
1021
1022 pub fn init(client: &Arc<Client>, cx: &mut App) {
1023 connection_manager::init(client.clone(), cx);
1024 Self::init_settings(cx);
1025
1026 let client: AnyProtoClient = client.clone().into();
1027 client.add_entity_message_handler(Self::handle_add_collaborator);
1028 client.add_entity_message_handler(Self::handle_update_project_collaborator);
1029 client.add_entity_message_handler(Self::handle_remove_collaborator);
1030 client.add_entity_message_handler(Self::handle_update_project);
1031 client.add_entity_message_handler(Self::handle_unshare_project);
1032 client.add_entity_request_handler(Self::handle_update_buffer);
1033 client.add_entity_message_handler(Self::handle_update_worktree);
1034 client.add_entity_request_handler(Self::handle_synchronize_buffers);
1035
1036 client.add_entity_request_handler(Self::handle_search_candidate_buffers);
1037 client.add_entity_request_handler(Self::handle_open_buffer_by_id);
1038 client.add_entity_request_handler(Self::handle_open_buffer_by_path);
1039 client.add_entity_request_handler(Self::handle_open_new_buffer);
1040 client.add_entity_message_handler(Self::handle_create_buffer_for_peer);
1041 client.add_entity_message_handler(Self::handle_toggle_lsp_logs);
1042
1043 WorktreeStore::init(&client);
1044 BufferStore::init(&client);
1045 LspStore::init(&client);
1046 GitStore::init(&client);
1047 SettingsObserver::init(&client);
1048 TaskStore::init(Some(&client));
1049 ToolchainStore::init(&client);
1050 DapStore::init(&client, cx);
1051 BreakpointStore::init(&client);
1052 context_server_store::init(cx);
1053 }
1054
1055 pub fn local(
1056 client: Arc<Client>,
1057 node: NodeRuntime,
1058 user_store: Entity<UserStore>,
1059 languages: Arc<LanguageRegistry>,
1060 fs: Arc<dyn Fs>,
1061 env: Option<HashMap<String, String>>,
1062 cx: &mut App,
1063 ) -> Entity<Self> {
1064 cx.new(|cx: &mut Context<Self>| {
1065 let (tx, rx) = mpsc::unbounded();
1066 cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1067 .detach();
1068 let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1069 let worktree_store = cx.new(|_| WorktreeStore::local(false, fs.clone()));
1070 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1071 .detach();
1072
1073 let weak_self = cx.weak_entity();
1074 let context_server_store =
1075 cx.new(|cx| ContextServerStore::new(worktree_store.clone(), weak_self, cx));
1076
1077 let environment = cx.new(|cx| ProjectEnvironment::new(env, cx));
1078 let manifest_tree = ManifestTree::new(worktree_store.clone(), cx);
1079 let toolchain_store = cx.new(|cx| {
1080 ToolchainStore::local(
1081 languages.clone(),
1082 worktree_store.clone(),
1083 environment.clone(),
1084 manifest_tree.clone(),
1085 fs.clone(),
1086 cx,
1087 )
1088 });
1089
1090 let buffer_store = cx.new(|cx| BufferStore::local(worktree_store.clone(), cx));
1091 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1092 .detach();
1093
1094 let breakpoint_store =
1095 cx.new(|_| BreakpointStore::local(worktree_store.clone(), buffer_store.clone()));
1096
1097 let dap_store = cx.new(|cx| {
1098 DapStore::new_local(
1099 client.http_client(),
1100 node.clone(),
1101 fs.clone(),
1102 environment.clone(),
1103 toolchain_store.read(cx).as_language_toolchain_store(),
1104 worktree_store.clone(),
1105 breakpoint_store.clone(),
1106 false,
1107 cx,
1108 )
1109 });
1110 cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
1111
1112 let image_store = cx.new(|cx| ImageStore::local(worktree_store.clone(), cx));
1113 cx.subscribe(&image_store, Self::on_image_store_event)
1114 .detach();
1115
1116 let prettier_store = cx.new(|cx| {
1117 PrettierStore::new(
1118 node.clone(),
1119 fs.clone(),
1120 languages.clone(),
1121 worktree_store.clone(),
1122 cx,
1123 )
1124 });
1125
1126 let task_store = cx.new(|cx| {
1127 TaskStore::local(
1128 buffer_store.downgrade(),
1129 worktree_store.clone(),
1130 toolchain_store.read(cx).as_language_toolchain_store(),
1131 environment.clone(),
1132 cx,
1133 )
1134 });
1135
1136 let settings_observer = cx.new(|cx| {
1137 SettingsObserver::new_local(
1138 fs.clone(),
1139 worktree_store.clone(),
1140 task_store.clone(),
1141 cx,
1142 )
1143 });
1144 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1145 .detach();
1146
1147 let lsp_store = cx.new(|cx| {
1148 LspStore::new_local(
1149 buffer_store.clone(),
1150 worktree_store.clone(),
1151 prettier_store.clone(),
1152 toolchain_store
1153 .read(cx)
1154 .as_local_store()
1155 .expect("Toolchain store to be local")
1156 .clone(),
1157 environment.clone(),
1158 manifest_tree,
1159 languages.clone(),
1160 client.http_client(),
1161 fs.clone(),
1162 cx,
1163 )
1164 });
1165
1166 let git_store = cx.new(|cx| {
1167 GitStore::local(
1168 &worktree_store,
1169 buffer_store.clone(),
1170 environment.clone(),
1171 fs.clone(),
1172 cx,
1173 )
1174 });
1175
1176 let agent_server_store = cx.new(|cx| {
1177 AgentServerStore::local(
1178 node.clone(),
1179 fs.clone(),
1180 environment.clone(),
1181 client.http_client(),
1182 cx,
1183 )
1184 });
1185
1186 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1187
1188 Self {
1189 buffer_ordered_messages_tx: tx,
1190 collaborators: Default::default(),
1191 worktree_store,
1192 buffer_store,
1193 image_store,
1194 lsp_store,
1195 context_server_store,
1196 join_project_response_message_id: 0,
1197 client_state: ProjectClientState::Local,
1198 git_store,
1199 client_subscriptions: Vec::new(),
1200 _subscriptions: vec![cx.on_release(Self::release)],
1201 active_entry: None,
1202 snippets,
1203 languages,
1204 collab_client: client,
1205 task_store,
1206 user_store,
1207 settings_observer,
1208 fs,
1209 remote_client: None,
1210 breakpoint_store,
1211 dap_store,
1212 agent_server_store,
1213
1214 buffers_needing_diff: Default::default(),
1215 git_diff_debouncer: DebouncedDelay::new(),
1216 terminals: Terminals {
1217 local_handles: Vec::new(),
1218 },
1219 node: Some(node),
1220 search_history: Self::new_search_history(),
1221 environment,
1222 remotely_created_models: Default::default(),
1223
1224 search_included_history: Self::new_search_history(),
1225 search_excluded_history: Self::new_search_history(),
1226
1227 toolchain_store: Some(toolchain_store),
1228
1229 agent_location: None,
1230 encoding: Arc::new(std::sync::Mutex::new(encoding_rs::UTF_8)),
1231 }
1232 })
1233 }
1234
1235 pub fn remote(
1236 remote: Entity<RemoteClient>,
1237 client: Arc<Client>,
1238 node: NodeRuntime,
1239 user_store: Entity<UserStore>,
1240 languages: Arc<LanguageRegistry>,
1241 fs: Arc<dyn Fs>,
1242 cx: &mut App,
1243 ) -> Entity<Self> {
1244 cx.new(|cx: &mut Context<Self>| {
1245 let (tx, rx) = mpsc::unbounded();
1246 cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1247 .detach();
1248 let global_snippets_dir = paths::snippets_dir().to_owned();
1249 let snippets =
1250 SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
1251
1252 let (remote_proto, path_style) =
1253 remote.read_with(cx, |remote, _| (remote.proto_client(), remote.path_style()));
1254 let worktree_store = cx.new(|_| {
1255 WorktreeStore::remote(
1256 false,
1257 remote_proto.clone(),
1258 REMOTE_SERVER_PROJECT_ID,
1259 path_style,
1260 )
1261 });
1262 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1263 .detach();
1264
1265 let weak_self = cx.weak_entity();
1266 let context_server_store =
1267 cx.new(|cx| ContextServerStore::new(worktree_store.clone(), weak_self, cx));
1268
1269 let buffer_store = cx.new(|cx| {
1270 BufferStore::remote(
1271 worktree_store.clone(),
1272 remote.read(cx).proto_client(),
1273 REMOTE_SERVER_PROJECT_ID,
1274 cx,
1275 )
1276 });
1277 let image_store = cx.new(|cx| {
1278 ImageStore::remote(
1279 worktree_store.clone(),
1280 remote.read(cx).proto_client(),
1281 REMOTE_SERVER_PROJECT_ID,
1282 cx,
1283 )
1284 });
1285 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1286 .detach();
1287 let toolchain_store = cx.new(|cx| {
1288 ToolchainStore::remote(REMOTE_SERVER_PROJECT_ID, remote.read(cx).proto_client(), cx)
1289 });
1290 let task_store = cx.new(|cx| {
1291 TaskStore::remote(
1292 buffer_store.downgrade(),
1293 worktree_store.clone(),
1294 toolchain_store.read(cx).as_language_toolchain_store(),
1295 remote.read(cx).proto_client(),
1296 REMOTE_SERVER_PROJECT_ID,
1297 cx,
1298 )
1299 });
1300
1301 let settings_observer = cx.new(|cx| {
1302 SettingsObserver::new_remote(
1303 fs.clone(),
1304 worktree_store.clone(),
1305 task_store.clone(),
1306 Some(remote_proto.clone()),
1307 cx,
1308 )
1309 });
1310 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1311 .detach();
1312
1313 let environment = cx.new(|cx| ProjectEnvironment::new(None, cx));
1314
1315 let lsp_store = cx.new(|cx| {
1316 LspStore::new_remote(
1317 buffer_store.clone(),
1318 worktree_store.clone(),
1319 languages.clone(),
1320 remote_proto.clone(),
1321 REMOTE_SERVER_PROJECT_ID,
1322 cx,
1323 )
1324 });
1325 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1326
1327 let breakpoint_store =
1328 cx.new(|_| BreakpointStore::remote(REMOTE_SERVER_PROJECT_ID, remote_proto.clone()));
1329
1330 let dap_store = cx.new(|cx| {
1331 DapStore::new_remote(
1332 REMOTE_SERVER_PROJECT_ID,
1333 remote.clone(),
1334 breakpoint_store.clone(),
1335 worktree_store.clone(),
1336 node.clone(),
1337 client.http_client(),
1338 fs.clone(),
1339 cx,
1340 )
1341 });
1342
1343 let git_store = cx.new(|cx| {
1344 GitStore::remote(
1345 &worktree_store,
1346 buffer_store.clone(),
1347 remote_proto.clone(),
1348 REMOTE_SERVER_PROJECT_ID,
1349 cx,
1350 )
1351 });
1352
1353 let agent_server_store =
1354 cx.new(|_| AgentServerStore::remote(REMOTE_SERVER_PROJECT_ID, remote.clone()));
1355
1356 cx.subscribe(&remote, Self::on_remote_client_event).detach();
1357
1358 let this = Self {
1359 buffer_ordered_messages_tx: tx,
1360 collaborators: Default::default(),
1361 worktree_store,
1362 buffer_store,
1363 image_store,
1364 lsp_store,
1365 context_server_store,
1366 breakpoint_store,
1367 dap_store,
1368 join_project_response_message_id: 0,
1369 client_state: ProjectClientState::Local,
1370 git_store,
1371 agent_server_store,
1372 client_subscriptions: Vec::new(),
1373 _subscriptions: vec![
1374 cx.on_release(Self::release),
1375 cx.on_app_quit(|this, cx| {
1376 let shutdown = this.remote_client.take().and_then(|client| {
1377 client.update(cx, |client, cx| {
1378 client.shutdown_processes(
1379 Some(proto::ShutdownRemoteServer {}),
1380 cx.background_executor().clone(),
1381 )
1382 })
1383 });
1384
1385 cx.background_executor().spawn(async move {
1386 if let Some(shutdown) = shutdown {
1387 shutdown.await;
1388 }
1389 })
1390 }),
1391 ],
1392 active_entry: None,
1393 snippets,
1394 languages,
1395 collab_client: client,
1396 task_store,
1397 user_store,
1398 settings_observer,
1399 fs,
1400 remote_client: Some(remote.clone()),
1401 buffers_needing_diff: Default::default(),
1402 git_diff_debouncer: DebouncedDelay::new(),
1403 terminals: Terminals {
1404 local_handles: Vec::new(),
1405 },
1406 node: Some(node),
1407 search_history: Self::new_search_history(),
1408 environment,
1409 remotely_created_models: Default::default(),
1410
1411 search_included_history: Self::new_search_history(),
1412 search_excluded_history: Self::new_search_history(),
1413
1414 toolchain_store: Some(toolchain_store),
1415 agent_location: None,
1416 encoding: Arc::new(std::sync::Mutex::new(encoding_rs::UTF_8)),
1417 };
1418
1419 // remote server -> local machine handlers
1420 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &cx.entity());
1421 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.buffer_store);
1422 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.worktree_store);
1423 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.lsp_store);
1424 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.dap_store);
1425 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.settings_observer);
1426 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.git_store);
1427 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.agent_server_store);
1428
1429 remote_proto.add_entity_message_handler(Self::handle_create_buffer_for_peer);
1430 remote_proto.add_entity_message_handler(Self::handle_update_worktree);
1431 remote_proto.add_entity_message_handler(Self::handle_update_project);
1432 remote_proto.add_entity_message_handler(Self::handle_toast);
1433 remote_proto.add_entity_request_handler(Self::handle_language_server_prompt_request);
1434 remote_proto.add_entity_message_handler(Self::handle_hide_toast);
1435 remote_proto.add_entity_request_handler(Self::handle_update_buffer_from_remote_server);
1436 BufferStore::init(&remote_proto);
1437 LspStore::init(&remote_proto);
1438 SettingsObserver::init(&remote_proto);
1439 TaskStore::init(Some(&remote_proto));
1440 ToolchainStore::init(&remote_proto);
1441 DapStore::init(&remote_proto, cx);
1442 GitStore::init(&remote_proto);
1443 AgentServerStore::init_remote(&remote_proto);
1444
1445 this
1446 })
1447 }
1448
1449 pub async fn in_room(
1450 remote_id: u64,
1451 client: Arc<Client>,
1452 user_store: Entity<UserStore>,
1453 languages: Arc<LanguageRegistry>,
1454 fs: Arc<dyn Fs>,
1455 cx: AsyncApp,
1456 ) -> Result<Entity<Self>> {
1457 client.connect(true, &cx).await.into_response()?;
1458
1459 let subscriptions = [
1460 EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
1461 EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
1462 EntitySubscription::GitStore(client.subscribe_to_entity::<GitStore>(remote_id)?),
1463 EntitySubscription::WorktreeStore(
1464 client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
1465 ),
1466 EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
1467 EntitySubscription::SettingsObserver(
1468 client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
1469 ),
1470 EntitySubscription::DapStore(client.subscribe_to_entity::<DapStore>(remote_id)?),
1471 ];
1472 let committer = get_git_committer(&cx).await;
1473 let response = client
1474 .request_envelope(proto::JoinProject {
1475 project_id: remote_id,
1476 committer_email: committer.email,
1477 committer_name: committer.name,
1478 })
1479 .await?;
1480 Self::from_join_project_response(
1481 response,
1482 subscriptions,
1483 client,
1484 false,
1485 user_store,
1486 languages,
1487 fs,
1488 cx,
1489 )
1490 .await
1491 }
1492
1493 async fn from_join_project_response(
1494 response: TypedEnvelope<proto::JoinProjectResponse>,
1495 subscriptions: [EntitySubscription; 7],
1496 client: Arc<Client>,
1497 run_tasks: bool,
1498 user_store: Entity<UserStore>,
1499 languages: Arc<LanguageRegistry>,
1500 fs: Arc<dyn Fs>,
1501 mut cx: AsyncApp,
1502 ) -> Result<Entity<Self>> {
1503 let remote_id = response.payload.project_id;
1504 let role = response.payload.role();
1505
1506 let path_style = if response.payload.windows_paths {
1507 PathStyle::Windows
1508 } else {
1509 PathStyle::Posix
1510 };
1511
1512 let worktree_store = cx.new(|_| {
1513 WorktreeStore::remote(
1514 true,
1515 client.clone().into(),
1516 response.payload.project_id,
1517 path_style,
1518 )
1519 })?;
1520 let buffer_store = cx.new(|cx| {
1521 BufferStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1522 })?;
1523 let image_store = cx.new(|cx| {
1524 ImageStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1525 })?;
1526
1527 let environment = cx.new(|cx| ProjectEnvironment::new(None, cx))?;
1528
1529 let breakpoint_store =
1530 cx.new(|_| BreakpointStore::remote(remote_id, client.clone().into()))?;
1531 let dap_store = cx.new(|cx| {
1532 DapStore::new_collab(
1533 remote_id,
1534 client.clone().into(),
1535 breakpoint_store.clone(),
1536 worktree_store.clone(),
1537 fs.clone(),
1538 cx,
1539 )
1540 })?;
1541
1542 let lsp_store = cx.new(|cx| {
1543 LspStore::new_remote(
1544 buffer_store.clone(),
1545 worktree_store.clone(),
1546 languages.clone(),
1547 client.clone().into(),
1548 remote_id,
1549 cx,
1550 )
1551 })?;
1552
1553 let task_store = cx.new(|cx| {
1554 if run_tasks {
1555 TaskStore::remote(
1556 buffer_store.downgrade(),
1557 worktree_store.clone(),
1558 Arc::new(EmptyToolchainStore),
1559 client.clone().into(),
1560 remote_id,
1561 cx,
1562 )
1563 } else {
1564 TaskStore::Noop
1565 }
1566 })?;
1567
1568 let settings_observer = cx.new(|cx| {
1569 SettingsObserver::new_remote(
1570 fs.clone(),
1571 worktree_store.clone(),
1572 task_store.clone(),
1573 None,
1574 cx,
1575 )
1576 })?;
1577
1578 let git_store = cx.new(|cx| {
1579 GitStore::remote(
1580 // In this remote case we pass None for the environment
1581 &worktree_store,
1582 buffer_store.clone(),
1583 client.clone().into(),
1584 remote_id,
1585 cx,
1586 )
1587 })?;
1588
1589 let agent_server_store = cx.new(|cx| AgentServerStore::collab(cx))?;
1590 let replica_id = ReplicaId::new(response.payload.replica_id as u16);
1591
1592 let project = cx.new(|cx| {
1593 let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1594
1595 let weak_self = cx.weak_entity();
1596 let context_server_store =
1597 cx.new(|cx| ContextServerStore::new(worktree_store.clone(), weak_self, cx));
1598
1599 let mut worktrees = Vec::new();
1600 for worktree in response.payload.worktrees {
1601 let worktree = Worktree::remote(
1602 remote_id,
1603 replica_id,
1604 worktree,
1605 client.clone().into(),
1606 path_style,
1607 cx,
1608 );
1609 worktrees.push(worktree);
1610 }
1611
1612 let (tx, rx) = mpsc::unbounded();
1613 cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1614 .detach();
1615
1616 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1617 .detach();
1618
1619 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1620 .detach();
1621 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1622 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1623 .detach();
1624
1625 cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
1626
1627 let mut project = Self {
1628 buffer_ordered_messages_tx: tx,
1629 buffer_store: buffer_store.clone(),
1630 image_store,
1631 worktree_store: worktree_store.clone(),
1632 lsp_store: lsp_store.clone(),
1633 context_server_store,
1634 active_entry: None,
1635 collaborators: Default::default(),
1636 join_project_response_message_id: response.message_id,
1637 languages,
1638 user_store: user_store.clone(),
1639 task_store,
1640 snippets,
1641 fs,
1642 remote_client: None,
1643 settings_observer: settings_observer.clone(),
1644 client_subscriptions: Default::default(),
1645 _subscriptions: vec![cx.on_release(Self::release)],
1646 collab_client: client.clone(),
1647 client_state: ProjectClientState::Remote {
1648 sharing_has_stopped: false,
1649 capability: Capability::ReadWrite,
1650 remote_id,
1651 replica_id,
1652 },
1653 breakpoint_store,
1654 dap_store: dap_store.clone(),
1655 git_store: git_store.clone(),
1656 agent_server_store,
1657 buffers_needing_diff: Default::default(),
1658 git_diff_debouncer: DebouncedDelay::new(),
1659 terminals: Terminals {
1660 local_handles: Vec::new(),
1661 },
1662 node: None,
1663 search_history: Self::new_search_history(),
1664 search_included_history: Self::new_search_history(),
1665 search_excluded_history: Self::new_search_history(),
1666 environment,
1667 remotely_created_models: Arc::new(Mutex::new(RemotelyCreatedModels::default())),
1668 toolchain_store: None,
1669 agent_location: None,
1670 encoding: Arc::new(std::sync::Mutex::new(encoding_rs::UTF_8)),
1671 };
1672 project.set_role(role, cx);
1673 for worktree in worktrees {
1674 project.add_worktree(&worktree, cx);
1675 }
1676 project
1677 })?;
1678
1679 let weak_project = project.downgrade();
1680 lsp_store
1681 .update(&mut cx, |lsp_store, cx| {
1682 lsp_store.set_language_server_statuses_from_proto(
1683 weak_project,
1684 response.payload.language_servers,
1685 response.payload.language_server_capabilities,
1686 cx,
1687 );
1688 })
1689 .ok();
1690
1691 let subscriptions = subscriptions
1692 .into_iter()
1693 .map(|s| match s {
1694 EntitySubscription::BufferStore(subscription) => {
1695 subscription.set_entity(&buffer_store, &cx)
1696 }
1697 EntitySubscription::WorktreeStore(subscription) => {
1698 subscription.set_entity(&worktree_store, &cx)
1699 }
1700 EntitySubscription::GitStore(subscription) => {
1701 subscription.set_entity(&git_store, &cx)
1702 }
1703 EntitySubscription::SettingsObserver(subscription) => {
1704 subscription.set_entity(&settings_observer, &cx)
1705 }
1706 EntitySubscription::Project(subscription) => subscription.set_entity(&project, &cx),
1707 EntitySubscription::LspStore(subscription) => {
1708 subscription.set_entity(&lsp_store, &cx)
1709 }
1710 EntitySubscription::DapStore(subscription) => {
1711 subscription.set_entity(&dap_store, &cx)
1712 }
1713 })
1714 .collect::<Vec<_>>();
1715
1716 let user_ids = response
1717 .payload
1718 .collaborators
1719 .iter()
1720 .map(|peer| peer.user_id)
1721 .collect();
1722 user_store
1723 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
1724 .await?;
1725
1726 project.update(&mut cx, |this, cx| {
1727 this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1728 this.client_subscriptions.extend(subscriptions);
1729 anyhow::Ok(())
1730 })??;
1731
1732 Ok(project)
1733 }
1734
1735 fn new_search_history() -> SearchHistory {
1736 SearchHistory::new(
1737 Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1738 search_history::QueryInsertionBehavior::AlwaysInsert,
1739 )
1740 }
1741
1742 fn release(&mut self, cx: &mut App) {
1743 if let Some(client) = self.remote_client.take() {
1744 let shutdown = client.update(cx, |client, cx| {
1745 client.shutdown_processes(
1746 Some(proto::ShutdownRemoteServer {}),
1747 cx.background_executor().clone(),
1748 )
1749 });
1750
1751 cx.background_spawn(async move {
1752 if let Some(shutdown) = shutdown {
1753 shutdown.await;
1754 }
1755 })
1756 .detach()
1757 }
1758
1759 match &self.client_state {
1760 ProjectClientState::Local => {}
1761 ProjectClientState::Shared { .. } => {
1762 let _ = self.unshare_internal(cx);
1763 }
1764 ProjectClientState::Remote { remote_id, .. } => {
1765 let _ = self.collab_client.send(proto::LeaveProject {
1766 project_id: *remote_id,
1767 });
1768 self.disconnected_from_host_internal(cx);
1769 }
1770 }
1771 }
1772
1773 #[cfg(any(test, feature = "test-support"))]
1774 pub async fn example(
1775 root_paths: impl IntoIterator<Item = &Path>,
1776 cx: &mut AsyncApp,
1777 ) -> Entity<Project> {
1778 use clock::FakeSystemClock;
1779
1780 let fs = Arc::new(RealFs::new(None, cx.background_executor().clone()));
1781 let languages = LanguageRegistry::test(cx.background_executor().clone());
1782 let clock = Arc::new(FakeSystemClock::new());
1783 let http_client = http_client::FakeHttpClient::with_404_response();
1784 let client = cx
1785 .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1786 .unwrap();
1787 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx)).unwrap();
1788 let project = cx
1789 .update(|cx| {
1790 Project::local(
1791 client,
1792 node_runtime::NodeRuntime::unavailable(),
1793 user_store,
1794 Arc::new(languages),
1795 fs,
1796 None,
1797 cx,
1798 )
1799 })
1800 .unwrap();
1801 for path in root_paths {
1802 let (tree, _) = project
1803 .update(cx, |project, cx| {
1804 project.find_or_create_worktree(path, true, cx)
1805 })
1806 .unwrap()
1807 .await
1808 .unwrap();
1809 tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1810 .unwrap()
1811 .await;
1812 }
1813 project
1814 }
1815
1816 #[cfg(any(test, feature = "test-support"))]
1817 pub async fn test(
1818 fs: Arc<dyn Fs>,
1819 root_paths: impl IntoIterator<Item = &Path>,
1820 cx: &mut gpui::TestAppContext,
1821 ) -> Entity<Project> {
1822 use clock::FakeSystemClock;
1823
1824 let languages = LanguageRegistry::test(cx.executor());
1825 let clock = Arc::new(FakeSystemClock::new());
1826 let http_client = http_client::FakeHttpClient::with_404_response();
1827 let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1828 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1829 let project = cx.update(|cx| {
1830 Project::local(
1831 client,
1832 node_runtime::NodeRuntime::unavailable(),
1833 user_store,
1834 Arc::new(languages),
1835 fs,
1836 None,
1837 cx,
1838 )
1839 });
1840 for path in root_paths {
1841 let (tree, _) = project
1842 .update(cx, |project, cx| {
1843 project.find_or_create_worktree(path, true, cx)
1844 })
1845 .await
1846 .unwrap();
1847
1848 tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1849 .await;
1850 }
1851 project
1852 }
1853
1854 #[inline]
1855 pub fn dap_store(&self) -> Entity<DapStore> {
1856 self.dap_store.clone()
1857 }
1858
1859 #[inline]
1860 pub fn breakpoint_store(&self) -> Entity<BreakpointStore> {
1861 self.breakpoint_store.clone()
1862 }
1863
1864 pub fn active_debug_session(&self, cx: &App) -> Option<(Entity<Session>, ActiveStackFrame)> {
1865 let active_position = self.breakpoint_store.read(cx).active_position()?;
1866 let session = self
1867 .dap_store
1868 .read(cx)
1869 .session_by_id(active_position.session_id)?;
1870 Some((session, active_position.clone()))
1871 }
1872
1873 #[inline]
1874 pub fn lsp_store(&self) -> Entity<LspStore> {
1875 self.lsp_store.clone()
1876 }
1877
1878 #[inline]
1879 pub fn worktree_store(&self) -> Entity<WorktreeStore> {
1880 self.worktree_store.clone()
1881 }
1882
1883 #[inline]
1884 pub fn context_server_store(&self) -> Entity<ContextServerStore> {
1885 self.context_server_store.clone()
1886 }
1887
1888 #[inline]
1889 pub fn buffer_for_id(&self, remote_id: BufferId, cx: &App) -> Option<Entity<Buffer>> {
1890 self.buffer_store.read(cx).get(remote_id)
1891 }
1892
1893 #[inline]
1894 pub fn languages(&self) -> &Arc<LanguageRegistry> {
1895 &self.languages
1896 }
1897
1898 #[inline]
1899 pub fn client(&self) -> Arc<Client> {
1900 self.collab_client.clone()
1901 }
1902
1903 #[inline]
1904 pub fn remote_client(&self) -> Option<Entity<RemoteClient>> {
1905 self.remote_client.clone()
1906 }
1907
1908 #[inline]
1909 pub fn user_store(&self) -> Entity<UserStore> {
1910 self.user_store.clone()
1911 }
1912
1913 #[inline]
1914 pub fn node_runtime(&self) -> Option<&NodeRuntime> {
1915 self.node.as_ref()
1916 }
1917
1918 #[inline]
1919 pub fn opened_buffers(&self, cx: &App) -> Vec<Entity<Buffer>> {
1920 self.buffer_store.read(cx).buffers().collect()
1921 }
1922
1923 #[inline]
1924 pub fn environment(&self) -> &Entity<ProjectEnvironment> {
1925 &self.environment
1926 }
1927
1928 #[inline]
1929 pub fn cli_environment(&self, cx: &App) -> Option<HashMap<String, String>> {
1930 self.environment.read(cx).get_cli_environment()
1931 }
1932
1933 pub fn buffer_environment<'a>(
1934 &'a self,
1935 buffer: &Entity<Buffer>,
1936 worktree_store: &Entity<WorktreeStore>,
1937 cx: &'a mut App,
1938 ) -> Shared<Task<Option<HashMap<String, String>>>> {
1939 self.environment.update(cx, |environment, cx| {
1940 environment.get_buffer_environment(buffer, worktree_store, cx)
1941 })
1942 }
1943
1944 pub fn directory_environment(
1945 &self,
1946 shell: &Shell,
1947 abs_path: Arc<Path>,
1948 cx: &mut App,
1949 ) -> Shared<Task<Option<HashMap<String, String>>>> {
1950 self.environment.update(cx, |environment, cx| {
1951 if let Some(remote_client) = self.remote_client.clone() {
1952 environment.get_remote_directory_environment(shell, abs_path, remote_client, cx)
1953 } else {
1954 environment.get_local_directory_environment(shell, abs_path, cx)
1955 }
1956 })
1957 }
1958
1959 #[inline]
1960 pub fn peek_environment_error<'a>(&'a self, cx: &'a App) -> Option<&'a String> {
1961 self.environment.read(cx).peek_environment_error()
1962 }
1963
1964 #[inline]
1965 pub fn pop_environment_error(&mut self, cx: &mut Context<Self>) {
1966 self.environment.update(cx, |environment, _| {
1967 environment.pop_environment_error();
1968 });
1969 }
1970
1971 #[cfg(any(test, feature = "test-support"))]
1972 #[inline]
1973 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
1974 self.buffer_store
1975 .read(cx)
1976 .get_by_path(&path.into())
1977 .is_some()
1978 }
1979
1980 #[inline]
1981 pub fn fs(&self) -> &Arc<dyn Fs> {
1982 &self.fs
1983 }
1984
1985 #[inline]
1986 pub fn remote_id(&self) -> Option<u64> {
1987 match self.client_state {
1988 ProjectClientState::Local => None,
1989 ProjectClientState::Shared { remote_id, .. }
1990 | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1991 }
1992 }
1993
1994 #[inline]
1995 pub fn supports_terminal(&self, _cx: &App) -> bool {
1996 if self.is_local() {
1997 return true;
1998 }
1999 if self.is_via_remote_server() {
2000 return true;
2001 }
2002
2003 false
2004 }
2005
2006 #[inline]
2007 pub fn remote_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
2008 self.remote_client
2009 .as_ref()
2010 .map(|remote| remote.read(cx).connection_state())
2011 }
2012
2013 #[inline]
2014 pub fn remote_connection_options(&self, cx: &App) -> Option<RemoteConnectionOptions> {
2015 self.remote_client
2016 .as_ref()
2017 .map(|remote| remote.read(cx).connection_options())
2018 }
2019
2020 #[inline]
2021 pub fn replica_id(&self) -> ReplicaId {
2022 match self.client_state {
2023 ProjectClientState::Remote { replica_id, .. } => replica_id,
2024 _ => {
2025 if self.remote_client.is_some() {
2026 ReplicaId::REMOTE_SERVER
2027 } else {
2028 ReplicaId::LOCAL
2029 }
2030 }
2031 }
2032 }
2033
2034 #[inline]
2035 pub fn task_store(&self) -> &Entity<TaskStore> {
2036 &self.task_store
2037 }
2038
2039 #[inline]
2040 pub fn snippets(&self) -> &Entity<SnippetProvider> {
2041 &self.snippets
2042 }
2043
2044 #[inline]
2045 pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
2046 match kind {
2047 SearchInputKind::Query => &self.search_history,
2048 SearchInputKind::Include => &self.search_included_history,
2049 SearchInputKind::Exclude => &self.search_excluded_history,
2050 }
2051 }
2052
2053 #[inline]
2054 pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
2055 match kind {
2056 SearchInputKind::Query => &mut self.search_history,
2057 SearchInputKind::Include => &mut self.search_included_history,
2058 SearchInputKind::Exclude => &mut self.search_excluded_history,
2059 }
2060 }
2061
2062 #[inline]
2063 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
2064 &self.collaborators
2065 }
2066
2067 #[inline]
2068 pub fn host(&self) -> Option<&Collaborator> {
2069 self.collaborators.values().find(|c| c.is_host)
2070 }
2071
2072 #[inline]
2073 pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
2074 self.worktree_store.update(cx, |store, _| {
2075 store.set_worktrees_reordered(worktrees_reordered);
2076 });
2077 }
2078
2079 /// Collect all worktrees, including ones that don't appear in the project panel
2080 #[inline]
2081 pub fn worktrees<'a>(
2082 &self,
2083 cx: &'a App,
2084 ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
2085 self.worktree_store.read(cx).worktrees()
2086 }
2087
2088 /// Collect all user-visible worktrees, the ones that appear in the project panel.
2089 #[inline]
2090 pub fn visible_worktrees<'a>(
2091 &'a self,
2092 cx: &'a App,
2093 ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
2094 self.worktree_store.read(cx).visible_worktrees(cx)
2095 }
2096
2097 #[inline]
2098 pub fn worktree_for_root_name(&self, root_name: &str, cx: &App) -> Option<Entity<Worktree>> {
2099 self.visible_worktrees(cx)
2100 .find(|tree| tree.read(cx).root_name() == root_name)
2101 }
2102
2103 #[inline]
2104 pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
2105 self.visible_worktrees(cx)
2106 .map(|tree| tree.read(cx).root_name().as_unix_str())
2107 }
2108
2109 #[inline]
2110 pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
2111 self.worktree_store.read(cx).worktree_for_id(id, cx)
2112 }
2113
2114 pub fn worktree_for_entry(
2115 &self,
2116 entry_id: ProjectEntryId,
2117 cx: &App,
2118 ) -> Option<Entity<Worktree>> {
2119 self.worktree_store
2120 .read(cx)
2121 .worktree_for_entry(entry_id, cx)
2122 }
2123
2124 #[inline]
2125 pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
2126 self.worktree_for_entry(entry_id, cx)
2127 .map(|worktree| worktree.read(cx).id())
2128 }
2129
2130 /// Checks if the entry is the root of a worktree.
2131 #[inline]
2132 pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
2133 self.worktree_for_entry(entry_id, cx)
2134 .map(|worktree| {
2135 worktree
2136 .read(cx)
2137 .root_entry()
2138 .is_some_and(|e| e.id == entry_id)
2139 })
2140 .unwrap_or(false)
2141 }
2142
2143 #[inline]
2144 pub fn project_path_git_status(
2145 &self,
2146 project_path: &ProjectPath,
2147 cx: &App,
2148 ) -> Option<FileStatus> {
2149 self.git_store
2150 .read(cx)
2151 .project_path_git_status(project_path, cx)
2152 }
2153
2154 #[inline]
2155 pub fn visibility_for_paths(
2156 &self,
2157 paths: &[PathBuf],
2158 metadatas: &[Metadata],
2159 exclude_sub_dirs: bool,
2160 cx: &App,
2161 ) -> Option<bool> {
2162 paths
2163 .iter()
2164 .zip(metadatas)
2165 .map(|(path, metadata)| self.visibility_for_path(path, metadata, exclude_sub_dirs, cx))
2166 .max()
2167 .flatten()
2168 }
2169
2170 pub fn visibility_for_path(
2171 &self,
2172 path: &Path,
2173 metadata: &Metadata,
2174 exclude_sub_dirs: bool,
2175 cx: &App,
2176 ) -> Option<bool> {
2177 let path = SanitizedPath::new(path).as_path();
2178 self.worktrees(cx)
2179 .filter_map(|worktree| {
2180 let worktree = worktree.read(cx);
2181 let abs_path = worktree.as_local()?.abs_path();
2182 let contains = path == abs_path.as_ref()
2183 || (path.starts_with(abs_path) && (!exclude_sub_dirs || !metadata.is_dir));
2184 contains.then(|| worktree.is_visible())
2185 })
2186 .max()
2187 }
2188
2189 pub fn create_entry(
2190 &mut self,
2191 project_path: impl Into<ProjectPath>,
2192 is_directory: bool,
2193 cx: &mut Context<Self>,
2194 ) -> Task<Result<CreatedEntry>> {
2195 let project_path = project_path.into();
2196 let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
2197 return Task::ready(Err(anyhow!(format!(
2198 "No worktree for path {project_path:?}"
2199 ))));
2200 };
2201 worktree.update(cx, |worktree, cx| {
2202 worktree.create_entry(project_path.path, is_directory, None, cx)
2203 })
2204 }
2205
2206 #[inline]
2207 pub fn copy_entry(
2208 &mut self,
2209 entry_id: ProjectEntryId,
2210 new_project_path: ProjectPath,
2211 cx: &mut Context<Self>,
2212 ) -> Task<Result<Option<Entry>>> {
2213 self.worktree_store.update(cx, |worktree_store, cx| {
2214 worktree_store.copy_entry(entry_id, new_project_path, cx)
2215 })
2216 }
2217
2218 /// Renames the project entry with given `entry_id`.
2219 ///
2220 /// `new_path` is a relative path to worktree root.
2221 /// If root entry is renamed then its new root name is used instead.
2222 pub fn rename_entry(
2223 &mut self,
2224 entry_id: ProjectEntryId,
2225 new_path: ProjectPath,
2226 cx: &mut Context<Self>,
2227 ) -> Task<Result<CreatedEntry>> {
2228 let worktree_store = self.worktree_store.clone();
2229 let Some((worktree, old_path, is_dir)) = worktree_store
2230 .read(cx)
2231 .worktree_and_entry_for_id(entry_id, cx)
2232 .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
2233 else {
2234 return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
2235 };
2236
2237 let worktree_id = worktree.read(cx).id();
2238 let is_root_entry = self.entry_is_worktree_root(entry_id, cx);
2239
2240 let lsp_store = self.lsp_store().downgrade();
2241 cx.spawn(async move |project, cx| {
2242 let (old_abs_path, new_abs_path) = {
2243 let root_path = worktree.read_with(cx, |this, _| this.abs_path())?;
2244 let new_abs_path = if is_root_entry {
2245 root_path
2246 .parent()
2247 .unwrap()
2248 .join(new_path.path.as_std_path())
2249 } else {
2250 root_path.join(&new_path.path.as_std_path())
2251 };
2252 (root_path.join(old_path.as_std_path()), new_abs_path)
2253 };
2254 let transaction = LspStore::will_rename_entry(
2255 lsp_store.clone(),
2256 worktree_id,
2257 &old_abs_path,
2258 &new_abs_path,
2259 is_dir,
2260 cx.clone(),
2261 )
2262 .await;
2263
2264 let entry = worktree_store
2265 .update(cx, |worktree_store, cx| {
2266 worktree_store.rename_entry(entry_id, new_path.clone(), cx)
2267 })?
2268 .await?;
2269
2270 project
2271 .update(cx, |_, cx| {
2272 cx.emit(Event::EntryRenamed(transaction));
2273 })
2274 .ok();
2275
2276 lsp_store
2277 .read_with(cx, |this, _| {
2278 this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
2279 })
2280 .ok();
2281 Ok(entry)
2282 })
2283 }
2284
2285 #[inline]
2286 pub fn delete_file(
2287 &mut self,
2288 path: ProjectPath,
2289 trash: bool,
2290 cx: &mut Context<Self>,
2291 ) -> Option<Task<Result<()>>> {
2292 let entry = self.entry_for_path(&path, cx)?;
2293 self.delete_entry(entry.id, trash, cx)
2294 }
2295
2296 #[inline]
2297 pub fn delete_entry(
2298 &mut self,
2299 entry_id: ProjectEntryId,
2300 trash: bool,
2301 cx: &mut Context<Self>,
2302 ) -> Option<Task<Result<()>>> {
2303 let worktree = self.worktree_for_entry(entry_id, cx)?;
2304 cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
2305 worktree.update(cx, |worktree, cx| {
2306 worktree.delete_entry(entry_id, trash, cx)
2307 })
2308 }
2309
2310 #[inline]
2311 pub fn expand_entry(
2312 &mut self,
2313 worktree_id: WorktreeId,
2314 entry_id: ProjectEntryId,
2315 cx: &mut Context<Self>,
2316 ) -> Option<Task<Result<()>>> {
2317 let worktree = self.worktree_for_id(worktree_id, cx)?;
2318 worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
2319 }
2320
2321 pub fn expand_all_for_entry(
2322 &mut self,
2323 worktree_id: WorktreeId,
2324 entry_id: ProjectEntryId,
2325 cx: &mut Context<Self>,
2326 ) -> Option<Task<Result<()>>> {
2327 let worktree = self.worktree_for_id(worktree_id, cx)?;
2328 let task = worktree.update(cx, |worktree, cx| {
2329 worktree.expand_all_for_entry(entry_id, cx)
2330 });
2331 Some(cx.spawn(async move |this, cx| {
2332 task.context("no task")?.await?;
2333 this.update(cx, |_, cx| {
2334 cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
2335 })?;
2336 Ok(())
2337 }))
2338 }
2339
2340 pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
2341 anyhow::ensure!(
2342 matches!(self.client_state, ProjectClientState::Local),
2343 "project was already shared"
2344 );
2345
2346 self.client_subscriptions.extend([
2347 self.collab_client
2348 .subscribe_to_entity(project_id)?
2349 .set_entity(&cx.entity(), &cx.to_async()),
2350 self.collab_client
2351 .subscribe_to_entity(project_id)?
2352 .set_entity(&self.worktree_store, &cx.to_async()),
2353 self.collab_client
2354 .subscribe_to_entity(project_id)?
2355 .set_entity(&self.buffer_store, &cx.to_async()),
2356 self.collab_client
2357 .subscribe_to_entity(project_id)?
2358 .set_entity(&self.lsp_store, &cx.to_async()),
2359 self.collab_client
2360 .subscribe_to_entity(project_id)?
2361 .set_entity(&self.settings_observer, &cx.to_async()),
2362 self.collab_client
2363 .subscribe_to_entity(project_id)?
2364 .set_entity(&self.dap_store, &cx.to_async()),
2365 self.collab_client
2366 .subscribe_to_entity(project_id)?
2367 .set_entity(&self.breakpoint_store, &cx.to_async()),
2368 self.collab_client
2369 .subscribe_to_entity(project_id)?
2370 .set_entity(&self.git_store, &cx.to_async()),
2371 ]);
2372
2373 self.buffer_store.update(cx, |buffer_store, cx| {
2374 buffer_store.shared(project_id, self.collab_client.clone().into(), cx)
2375 });
2376 self.worktree_store.update(cx, |worktree_store, cx| {
2377 worktree_store.shared(project_id, self.collab_client.clone().into(), cx);
2378 });
2379 self.lsp_store.update(cx, |lsp_store, cx| {
2380 lsp_store.shared(project_id, self.collab_client.clone().into(), cx)
2381 });
2382 self.breakpoint_store.update(cx, |breakpoint_store, _| {
2383 breakpoint_store.shared(project_id, self.collab_client.clone().into())
2384 });
2385 self.dap_store.update(cx, |dap_store, cx| {
2386 dap_store.shared(project_id, self.collab_client.clone().into(), cx);
2387 });
2388 self.task_store.update(cx, |task_store, cx| {
2389 task_store.shared(project_id, self.collab_client.clone().into(), cx);
2390 });
2391 self.settings_observer.update(cx, |settings_observer, cx| {
2392 settings_observer.shared(project_id, self.collab_client.clone().into(), cx)
2393 });
2394 self.git_store.update(cx, |git_store, cx| {
2395 git_store.shared(project_id, self.collab_client.clone().into(), cx)
2396 });
2397
2398 self.client_state = ProjectClientState::Shared {
2399 remote_id: project_id,
2400 };
2401
2402 cx.emit(Event::RemoteIdChanged(Some(project_id)));
2403 Ok(())
2404 }
2405
2406 pub fn reshared(
2407 &mut self,
2408 message: proto::ResharedProject,
2409 cx: &mut Context<Self>,
2410 ) -> Result<()> {
2411 self.buffer_store
2412 .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
2413 self.set_collaborators_from_proto(message.collaborators, cx)?;
2414
2415 self.worktree_store.update(cx, |worktree_store, cx| {
2416 worktree_store.send_project_updates(cx);
2417 });
2418 if let Some(remote_id) = self.remote_id() {
2419 self.git_store.update(cx, |git_store, cx| {
2420 git_store.shared(remote_id, self.collab_client.clone().into(), cx)
2421 });
2422 }
2423 cx.emit(Event::Reshared);
2424 Ok(())
2425 }
2426
2427 pub fn rejoined(
2428 &mut self,
2429 message: proto::RejoinedProject,
2430 message_id: u32,
2431 cx: &mut Context<Self>,
2432 ) -> Result<()> {
2433 cx.update_global::<SettingsStore, _>(|store, cx| {
2434 self.worktree_store.update(cx, |worktree_store, cx| {
2435 for worktree in worktree_store.worktrees() {
2436 store
2437 .clear_local_settings(worktree.read(cx).id(), cx)
2438 .log_err();
2439 }
2440 });
2441 });
2442
2443 self.join_project_response_message_id = message_id;
2444 self.set_worktrees_from_proto(message.worktrees, cx)?;
2445 self.set_collaborators_from_proto(message.collaborators, cx)?;
2446
2447 let project = cx.weak_entity();
2448 self.lsp_store.update(cx, |lsp_store, cx| {
2449 lsp_store.set_language_server_statuses_from_proto(
2450 project,
2451 message.language_servers,
2452 message.language_server_capabilities,
2453 cx,
2454 )
2455 });
2456 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
2457 .unwrap();
2458 cx.emit(Event::Rejoined);
2459 Ok(())
2460 }
2461
2462 #[inline]
2463 pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
2464 self.unshare_internal(cx)?;
2465 cx.emit(Event::RemoteIdChanged(None));
2466 Ok(())
2467 }
2468
2469 fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
2470 anyhow::ensure!(
2471 !self.is_via_collab(),
2472 "attempted to unshare a remote project"
2473 );
2474
2475 if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
2476 self.client_state = ProjectClientState::Local;
2477 self.collaborators.clear();
2478 self.client_subscriptions.clear();
2479 self.worktree_store.update(cx, |store, cx| {
2480 store.unshared(cx);
2481 });
2482 self.buffer_store.update(cx, |buffer_store, cx| {
2483 buffer_store.forget_shared_buffers();
2484 buffer_store.unshared(cx)
2485 });
2486 self.task_store.update(cx, |task_store, cx| {
2487 task_store.unshared(cx);
2488 });
2489 self.breakpoint_store.update(cx, |breakpoint_store, cx| {
2490 breakpoint_store.unshared(cx);
2491 });
2492 self.dap_store.update(cx, |dap_store, cx| {
2493 dap_store.unshared(cx);
2494 });
2495 self.settings_observer.update(cx, |settings_observer, cx| {
2496 settings_observer.unshared(cx);
2497 });
2498 self.git_store.update(cx, |git_store, cx| {
2499 git_store.unshared(cx);
2500 });
2501
2502 self.collab_client
2503 .send(proto::UnshareProject {
2504 project_id: remote_id,
2505 })
2506 .ok();
2507 Ok(())
2508 } else {
2509 anyhow::bail!("attempted to unshare an unshared project");
2510 }
2511 }
2512
2513 pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
2514 if self.is_disconnected(cx) {
2515 return;
2516 }
2517 self.disconnected_from_host_internal(cx);
2518 cx.emit(Event::DisconnectedFromHost);
2519 }
2520
2521 pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
2522 let new_capability =
2523 if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
2524 Capability::ReadWrite
2525 } else {
2526 Capability::ReadOnly
2527 };
2528 if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
2529 if *capability == new_capability {
2530 return;
2531 }
2532
2533 *capability = new_capability;
2534 for buffer in self.opened_buffers(cx) {
2535 buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
2536 }
2537 }
2538 }
2539
2540 fn disconnected_from_host_internal(&mut self, cx: &mut App) {
2541 if let ProjectClientState::Remote {
2542 sharing_has_stopped,
2543 ..
2544 } = &mut self.client_state
2545 {
2546 *sharing_has_stopped = true;
2547 self.collaborators.clear();
2548 self.worktree_store.update(cx, |store, cx| {
2549 store.disconnected_from_host(cx);
2550 });
2551 self.buffer_store.update(cx, |buffer_store, cx| {
2552 buffer_store.disconnected_from_host(cx)
2553 });
2554 self.lsp_store
2555 .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
2556 }
2557 }
2558
2559 #[inline]
2560 pub fn close(&mut self, cx: &mut Context<Self>) {
2561 cx.emit(Event::Closed);
2562 }
2563
2564 #[inline]
2565 pub fn is_disconnected(&self, cx: &App) -> bool {
2566 match &self.client_state {
2567 ProjectClientState::Remote {
2568 sharing_has_stopped,
2569 ..
2570 } => *sharing_has_stopped,
2571 ProjectClientState::Local if self.is_via_remote_server() => {
2572 self.remote_client_is_disconnected(cx)
2573 }
2574 _ => false,
2575 }
2576 }
2577
2578 #[inline]
2579 fn remote_client_is_disconnected(&self, cx: &App) -> bool {
2580 self.remote_client
2581 .as_ref()
2582 .map(|remote| remote.read(cx).is_disconnected())
2583 .unwrap_or(false)
2584 }
2585
2586 #[inline]
2587 pub fn capability(&self) -> Capability {
2588 match &self.client_state {
2589 ProjectClientState::Remote { capability, .. } => *capability,
2590 ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
2591 }
2592 }
2593
2594 #[inline]
2595 pub fn is_read_only(&self, cx: &App) -> bool {
2596 self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
2597 }
2598
2599 #[inline]
2600 pub fn is_local(&self) -> bool {
2601 match &self.client_state {
2602 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2603 self.remote_client.is_none()
2604 }
2605 ProjectClientState::Remote { .. } => false,
2606 }
2607 }
2608
2609 /// Whether this project is a remote server (not counting collab).
2610 #[inline]
2611 pub fn is_via_remote_server(&self) -> bool {
2612 match &self.client_state {
2613 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2614 self.remote_client.is_some()
2615 }
2616 ProjectClientState::Remote { .. } => false,
2617 }
2618 }
2619
2620 /// Whether this project is from collab (not counting remote servers).
2621 #[inline]
2622 pub fn is_via_collab(&self) -> bool {
2623 match &self.client_state {
2624 ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
2625 ProjectClientState::Remote { .. } => true,
2626 }
2627 }
2628
2629 /// `!self.is_local()`
2630 #[inline]
2631 pub fn is_remote(&self) -> bool {
2632 debug_assert_eq!(
2633 !self.is_local(),
2634 self.is_via_collab() || self.is_via_remote_server()
2635 );
2636 !self.is_local()
2637 }
2638
2639 #[inline]
2640 pub fn create_buffer(
2641 &mut self,
2642 searchable: bool,
2643 cx: &mut Context<Self>,
2644 ) -> Task<Result<Entity<Buffer>>> {
2645 self.buffer_store.update(cx, |buffer_store, cx| {
2646 buffer_store.create_buffer(searchable, cx)
2647 })
2648 }
2649
2650 #[inline]
2651 pub fn create_local_buffer(
2652 &mut self,
2653 text: &str,
2654 language: Option<Arc<Language>>,
2655 project_searchable: bool,
2656 cx: &mut Context<Self>,
2657 ) -> Entity<Buffer> {
2658 if self.is_remote() {
2659 panic!("called create_local_buffer on a remote project")
2660 }
2661 self.buffer_store.update(cx, |buffer_store, cx| {
2662 buffer_store.create_local_buffer(text, language, project_searchable, cx)
2663 })
2664 }
2665
2666 pub fn open_path(
2667 &mut self,
2668 path: ProjectPath,
2669 cx: &mut Context<Self>,
2670 ) -> Task<Result<(Option<ProjectEntryId>, Entity<Buffer>)>> {
2671 let task = self.open_buffer(path, cx);
2672 cx.spawn(async move |_project, cx| {
2673 let buffer = task.await?;
2674 let project_entry_id = buffer.read_with(cx, |buffer, _cx| {
2675 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id())
2676 })?;
2677
2678 Ok((project_entry_id, buffer))
2679 })
2680 }
2681
2682 pub fn open_local_buffer(
2683 &mut self,
2684 abs_path: impl AsRef<Path>,
2685 cx: &mut Context<Self>,
2686 ) -> Task<Result<Entity<Buffer>>> {
2687 let worktree_task = self.find_or_create_worktree(abs_path.as_ref(), false, cx);
2688 cx.spawn(async move |this, cx| {
2689 let (worktree, relative_path) = worktree_task.await?;
2690 this.update(cx, |this, cx| {
2691 this.open_buffer((worktree.read(cx).id(), relative_path), cx)
2692 })?
2693 .await
2694 })
2695 }
2696
2697 #[cfg(any(test, feature = "test-support"))]
2698 pub fn open_local_buffer_with_lsp(
2699 &mut self,
2700 abs_path: impl AsRef<Path>,
2701 cx: &mut Context<Self>,
2702 ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2703 if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2704 self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
2705 } else {
2706 Task::ready(Err(anyhow!("no such path")))
2707 }
2708 }
2709
2710 pub fn open_buffer(
2711 &mut self,
2712 path: impl Into<ProjectPath>,
2713 cx: &mut App,
2714 ) -> Task<Result<Entity<Buffer>>> {
2715 if self.is_disconnected(cx) {
2716 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2717 }
2718
2719 self.buffer_store.update(cx, |buffer_store, cx| {
2720 buffer_store.open_buffer(path.into(), cx)
2721 })
2722 }
2723
2724 #[cfg(any(test, feature = "test-support"))]
2725 pub fn open_buffer_with_lsp(
2726 &mut self,
2727 path: impl Into<ProjectPath>,
2728 cx: &mut Context<Self>,
2729 ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2730 let buffer = self.open_buffer(path, cx);
2731 cx.spawn(async move |this, cx| {
2732 let buffer = buffer.await?;
2733 let handle = this.update(cx, |project, cx| {
2734 project.register_buffer_with_language_servers(&buffer, cx)
2735 })?;
2736 Ok((buffer, handle))
2737 })
2738 }
2739
2740 pub fn register_buffer_with_language_servers(
2741 &self,
2742 buffer: &Entity<Buffer>,
2743 cx: &mut App,
2744 ) -> OpenLspBufferHandle {
2745 self.lsp_store.update(cx, |lsp_store, cx| {
2746 lsp_store.register_buffer_with_language_servers(buffer, HashSet::default(), false, cx)
2747 })
2748 }
2749
2750 pub fn open_unstaged_diff(
2751 &mut self,
2752 buffer: Entity<Buffer>,
2753 cx: &mut Context<Self>,
2754 ) -> Task<Result<Entity<BufferDiff>>> {
2755 if self.is_disconnected(cx) {
2756 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2757 }
2758 self.git_store
2759 .update(cx, |git_store, cx| git_store.open_unstaged_diff(buffer, cx))
2760 }
2761
2762 pub fn open_uncommitted_diff(
2763 &mut self,
2764 buffer: Entity<Buffer>,
2765 cx: &mut Context<Self>,
2766 ) -> Task<Result<Entity<BufferDiff>>> {
2767 if self.is_disconnected(cx) {
2768 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2769 }
2770 self.git_store.update(cx, |git_store, cx| {
2771 git_store.open_uncommitted_diff(buffer, cx)
2772 })
2773 }
2774
2775 pub fn open_buffer_by_id(
2776 &mut self,
2777 id: BufferId,
2778 cx: &mut Context<Self>,
2779 ) -> Task<Result<Entity<Buffer>>> {
2780 if let Some(buffer) = self.buffer_for_id(id, cx) {
2781 Task::ready(Ok(buffer))
2782 } else if self.is_local() || self.is_via_remote_server() {
2783 Task::ready(Err(anyhow!("buffer {id} does not exist")))
2784 } else if let Some(project_id) = self.remote_id() {
2785 let request = self.collab_client.request(proto::OpenBufferById {
2786 project_id,
2787 id: id.into(),
2788 });
2789 cx.spawn(async move |project, cx| {
2790 let buffer_id = BufferId::new(request.await?.buffer_id)?;
2791 project
2792 .update(cx, |project, cx| {
2793 project.buffer_store.update(cx, |buffer_store, cx| {
2794 buffer_store.wait_for_remote_buffer(buffer_id, cx)
2795 })
2796 })?
2797 .await
2798 })
2799 } else {
2800 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
2801 }
2802 }
2803
2804 pub fn save_buffers(
2805 &self,
2806 buffers: HashSet<Entity<Buffer>>,
2807 cx: &mut Context<Self>,
2808 ) -> Task<Result<()>> {
2809 cx.spawn(async move |this, cx| {
2810 let save_tasks = buffers.into_iter().filter_map(|buffer| {
2811 this.update(cx, |this, cx| this.save_buffer(buffer, cx))
2812 .ok()
2813 });
2814 try_join_all(save_tasks).await?;
2815 Ok(())
2816 })
2817 }
2818
2819 pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
2820 self.buffer_store
2821 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
2822 }
2823
2824 pub fn save_buffer_as(
2825 &mut self,
2826 buffer: Entity<Buffer>,
2827 path: ProjectPath,
2828 cx: &mut Context<Self>,
2829 ) -> Task<Result<()>> {
2830 self.buffer_store.update(cx, |buffer_store, cx| {
2831 buffer_store.save_buffer_as(buffer.clone(), path, cx)
2832 })
2833 }
2834
2835 pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
2836 self.buffer_store.read(cx).get_by_path(path)
2837 }
2838
2839 fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
2840 {
2841 let mut remotely_created_models = self.remotely_created_models.lock();
2842 if remotely_created_models.retain_count > 0 {
2843 remotely_created_models.buffers.push(buffer.clone())
2844 }
2845 }
2846
2847 self.request_buffer_diff_recalculation(buffer, cx);
2848
2849 cx.subscribe(buffer, |this, buffer, event, cx| {
2850 this.on_buffer_event(buffer, event, cx);
2851 })
2852 .detach();
2853
2854 Ok(())
2855 }
2856
2857 pub fn open_image(
2858 &mut self,
2859 path: impl Into<ProjectPath>,
2860 cx: &mut Context<Self>,
2861 ) -> Task<Result<Entity<ImageItem>>> {
2862 if self.is_disconnected(cx) {
2863 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2864 }
2865
2866 let open_image_task = self.image_store.update(cx, |image_store, cx| {
2867 image_store.open_image(path.into(), cx)
2868 });
2869
2870 let weak_project = cx.entity().downgrade();
2871 cx.spawn(async move |_, cx| {
2872 let image_item = open_image_task.await?;
2873 let project = weak_project.upgrade().context("Project dropped")?;
2874
2875 let metadata = ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
2876 image_item.update(cx, |image_item, cx| {
2877 image_item.image_metadata = Some(metadata);
2878 cx.emit(ImageItemEvent::MetadataUpdated);
2879 })?;
2880
2881 Ok(image_item)
2882 })
2883 }
2884
2885 async fn send_buffer_ordered_messages(
2886 project: WeakEntity<Self>,
2887 rx: UnboundedReceiver<BufferOrderedMessage>,
2888 cx: &mut AsyncApp,
2889 ) -> Result<()> {
2890 const MAX_BATCH_SIZE: usize = 128;
2891
2892 let mut operations_by_buffer_id = HashMap::default();
2893 async fn flush_operations(
2894 this: &WeakEntity<Project>,
2895 operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2896 needs_resync_with_host: &mut bool,
2897 is_local: bool,
2898 cx: &mut AsyncApp,
2899 ) -> Result<()> {
2900 for (buffer_id, operations) in operations_by_buffer_id.drain() {
2901 let request = this.read_with(cx, |this, _| {
2902 let project_id = this.remote_id()?;
2903 Some(this.collab_client.request(proto::UpdateBuffer {
2904 buffer_id: buffer_id.into(),
2905 project_id,
2906 operations,
2907 }))
2908 })?;
2909 if let Some(request) = request
2910 && request.await.is_err()
2911 && !is_local
2912 {
2913 *needs_resync_with_host = true;
2914 break;
2915 }
2916 }
2917 Ok(())
2918 }
2919
2920 let mut needs_resync_with_host = false;
2921 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2922
2923 while let Some(changes) = changes.next().await {
2924 let is_local = project.read_with(cx, |this, _| this.is_local())?;
2925
2926 for change in changes {
2927 match change {
2928 BufferOrderedMessage::Operation {
2929 buffer_id,
2930 operation,
2931 } => {
2932 if needs_resync_with_host {
2933 continue;
2934 }
2935
2936 operations_by_buffer_id
2937 .entry(buffer_id)
2938 .or_insert(Vec::new())
2939 .push(operation);
2940 }
2941
2942 BufferOrderedMessage::Resync => {
2943 operations_by_buffer_id.clear();
2944 if project
2945 .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
2946 .await
2947 .is_ok()
2948 {
2949 needs_resync_with_host = false;
2950 }
2951 }
2952
2953 BufferOrderedMessage::LanguageServerUpdate {
2954 language_server_id,
2955 message,
2956 name,
2957 } => {
2958 flush_operations(
2959 &project,
2960 &mut operations_by_buffer_id,
2961 &mut needs_resync_with_host,
2962 is_local,
2963 cx,
2964 )
2965 .await?;
2966
2967 project.read_with(cx, |project, _| {
2968 if let Some(project_id) = project.remote_id() {
2969 project
2970 .collab_client
2971 .send(proto::UpdateLanguageServer {
2972 project_id,
2973 server_name: name.map(|name| String::from(name.0)),
2974 language_server_id: language_server_id.to_proto(),
2975 variant: Some(message),
2976 })
2977 .log_err();
2978 }
2979 })?;
2980 }
2981 }
2982 }
2983
2984 flush_operations(
2985 &project,
2986 &mut operations_by_buffer_id,
2987 &mut needs_resync_with_host,
2988 is_local,
2989 cx,
2990 )
2991 .await?;
2992 }
2993
2994 Ok(())
2995 }
2996
2997 fn on_buffer_store_event(
2998 &mut self,
2999 _: Entity<BufferStore>,
3000 event: &BufferStoreEvent,
3001 cx: &mut Context<Self>,
3002 ) {
3003 match event {
3004 BufferStoreEvent::BufferAdded(buffer) => {
3005 self.register_buffer(buffer, cx).log_err();
3006 }
3007 BufferStoreEvent::BufferDropped(buffer_id) => {
3008 if let Some(ref remote_client) = self.remote_client {
3009 remote_client
3010 .read(cx)
3011 .proto_client()
3012 .send(proto::CloseBuffer {
3013 project_id: 0,
3014 buffer_id: buffer_id.to_proto(),
3015 })
3016 .log_err();
3017 }
3018 }
3019 _ => {}
3020 }
3021 }
3022
3023 fn on_image_store_event(
3024 &mut self,
3025 _: Entity<ImageStore>,
3026 event: &ImageStoreEvent,
3027 cx: &mut Context<Self>,
3028 ) {
3029 match event {
3030 ImageStoreEvent::ImageAdded(image) => {
3031 cx.subscribe(image, |this, image, event, cx| {
3032 this.on_image_event(image, event, cx);
3033 })
3034 .detach();
3035 }
3036 }
3037 }
3038
3039 fn on_dap_store_event(
3040 &mut self,
3041 _: Entity<DapStore>,
3042 event: &DapStoreEvent,
3043 cx: &mut Context<Self>,
3044 ) {
3045 if let DapStoreEvent::Notification(message) = event {
3046 cx.emit(Event::Toast {
3047 notification_id: "dap".into(),
3048 message: message.clone(),
3049 });
3050 }
3051 }
3052
3053 fn on_lsp_store_event(
3054 &mut self,
3055 _: Entity<LspStore>,
3056 event: &LspStoreEvent,
3057 cx: &mut Context<Self>,
3058 ) {
3059 match event {
3060 LspStoreEvent::DiagnosticsUpdated { server_id, paths } => {
3061 cx.emit(Event::DiagnosticsUpdated {
3062 paths: paths.clone(),
3063 language_server_id: *server_id,
3064 })
3065 }
3066 LspStoreEvent::LanguageServerAdded(server_id, name, worktree_id) => cx.emit(
3067 Event::LanguageServerAdded(*server_id, name.clone(), *worktree_id),
3068 ),
3069 LspStoreEvent::LanguageServerRemoved(server_id) => {
3070 cx.emit(Event::LanguageServerRemoved(*server_id))
3071 }
3072 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
3073 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
3074 ),
3075 LspStoreEvent::LanguageDetected {
3076 buffer,
3077 new_language,
3078 } => {
3079 let Some(_) = new_language else {
3080 cx.emit(Event::LanguageNotFound(buffer.clone()));
3081 return;
3082 };
3083 }
3084 LspStoreEvent::RefreshInlayHints(server_id) => {
3085 cx.emit(Event::RefreshInlayHints(*server_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<ProgressToken>,
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(
5413 rel_path.clone(),
5414 Rope::from_str(&new_text, cx.background_executor()),
5415 line_ending,
5416 cx,
5417 )
5418 })?
5419 .await
5420 .context("Failed to write settings file")?;
5421
5422 anyhow::Ok(())
5423 })
5424 .detach_and_log_err(cx);
5425 }
5426}
5427
5428pub struct PathMatchCandidateSet {
5429 pub snapshot: Snapshot,
5430 pub include_ignored: bool,
5431 pub include_root_name: bool,
5432 pub candidates: Candidates,
5433}
5434
5435pub enum Candidates {
5436 /// Only consider directories.
5437 Directories,
5438 /// Only consider files.
5439 Files,
5440 /// Consider directories and files.
5441 Entries,
5442}
5443
5444impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5445 type Candidates = PathMatchCandidateSetIter<'a>;
5446
5447 fn id(&self) -> usize {
5448 self.snapshot.id().to_usize()
5449 }
5450
5451 fn len(&self) -> usize {
5452 match self.candidates {
5453 Candidates::Files => {
5454 if self.include_ignored {
5455 self.snapshot.file_count()
5456 } else {
5457 self.snapshot.visible_file_count()
5458 }
5459 }
5460
5461 Candidates::Directories => {
5462 if self.include_ignored {
5463 self.snapshot.dir_count()
5464 } else {
5465 self.snapshot.visible_dir_count()
5466 }
5467 }
5468
5469 Candidates::Entries => {
5470 if self.include_ignored {
5471 self.snapshot.entry_count()
5472 } else {
5473 self.snapshot.visible_entry_count()
5474 }
5475 }
5476 }
5477 }
5478
5479 fn prefix(&self) -> Arc<RelPath> {
5480 if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
5481 self.snapshot.root_name().into()
5482 } else {
5483 RelPath::empty().into()
5484 }
5485 }
5486
5487 fn root_is_file(&self) -> bool {
5488 self.snapshot.root_entry().is_some_and(|f| f.is_file())
5489 }
5490
5491 fn path_style(&self) -> PathStyle {
5492 self.snapshot.path_style()
5493 }
5494
5495 fn candidates(&'a self, start: usize) -> Self::Candidates {
5496 PathMatchCandidateSetIter {
5497 traversal: match self.candidates {
5498 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5499 Candidates::Files => self.snapshot.files(self.include_ignored, start),
5500 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5501 },
5502 }
5503 }
5504}
5505
5506pub struct PathMatchCandidateSetIter<'a> {
5507 traversal: Traversal<'a>,
5508}
5509
5510impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5511 type Item = fuzzy::PathMatchCandidate<'a>;
5512
5513 fn next(&mut self) -> Option<Self::Item> {
5514 self.traversal
5515 .next()
5516 .map(|entry| fuzzy::PathMatchCandidate {
5517 is_dir: entry.kind.is_dir(),
5518 path: &entry.path,
5519 char_bag: entry.char_bag,
5520 })
5521 }
5522}
5523
5524impl EventEmitter<Event> for Project {}
5525
5526impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5527 fn from(val: &'a ProjectPath) -> Self {
5528 SettingsLocation {
5529 worktree_id: val.worktree_id,
5530 path: val.path.as_ref(),
5531 }
5532 }
5533}
5534
5535impl<P: Into<Arc<RelPath>>> From<(WorktreeId, P)> for ProjectPath {
5536 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5537 Self {
5538 worktree_id,
5539 path: path.into(),
5540 }
5541 }
5542}
5543
5544/// ResolvedPath is a path that has been resolved to either a ProjectPath
5545/// or an AbsPath and that *exists*.
5546#[derive(Debug, Clone)]
5547pub enum ResolvedPath {
5548 ProjectPath {
5549 project_path: ProjectPath,
5550 is_dir: bool,
5551 },
5552 AbsPath {
5553 path: String,
5554 is_dir: bool,
5555 },
5556}
5557
5558impl ResolvedPath {
5559 pub fn abs_path(&self) -> Option<&str> {
5560 match self {
5561 Self::AbsPath { path, .. } => Some(path),
5562 _ => None,
5563 }
5564 }
5565
5566 pub fn into_abs_path(self) -> Option<String> {
5567 match self {
5568 Self::AbsPath { path, .. } => Some(path),
5569 _ => None,
5570 }
5571 }
5572
5573 pub fn project_path(&self) -> Option<&ProjectPath> {
5574 match self {
5575 Self::ProjectPath { project_path, .. } => Some(project_path),
5576 _ => None,
5577 }
5578 }
5579
5580 pub fn is_file(&self) -> bool {
5581 !self.is_dir()
5582 }
5583
5584 pub fn is_dir(&self) -> bool {
5585 match self {
5586 Self::ProjectPath { is_dir, .. } => *is_dir,
5587 Self::AbsPath { is_dir, .. } => *is_dir,
5588 }
5589 }
5590}
5591
5592impl ProjectItem for Buffer {
5593 fn try_open(
5594 project: &Entity<Project>,
5595 path: &ProjectPath,
5596 cx: &mut App,
5597 ) -> Option<Task<Result<Entity<Self>>>> {
5598 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5599 }
5600
5601 fn entry_id(&self, _cx: &App) -> Option<ProjectEntryId> {
5602 File::from_dyn(self.file()).and_then(|file| file.project_entry_id())
5603 }
5604
5605 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5606 self.file().map(|file| ProjectPath {
5607 worktree_id: file.worktree_id(cx),
5608 path: file.path().clone(),
5609 })
5610 }
5611
5612 fn is_dirty(&self) -> bool {
5613 self.is_dirty()
5614 }
5615}
5616
5617impl Completion {
5618 pub fn kind(&self) -> Option<CompletionItemKind> {
5619 self.source
5620 // `lsp::CompletionListItemDefaults` has no `kind` field
5621 .lsp_completion(false)
5622 .and_then(|lsp_completion| lsp_completion.kind)
5623 }
5624
5625 pub fn label(&self) -> Option<String> {
5626 self.source
5627 .lsp_completion(false)
5628 .map(|lsp_completion| lsp_completion.label.clone())
5629 }
5630
5631 /// A key that can be used to sort completions when displaying
5632 /// them to the user.
5633 pub fn sort_key(&self) -> (usize, &str) {
5634 const DEFAULT_KIND_KEY: usize = 4;
5635 let kind_key = self
5636 .kind()
5637 .and_then(|lsp_completion_kind| match lsp_completion_kind {
5638 lsp::CompletionItemKind::KEYWORD => Some(0),
5639 lsp::CompletionItemKind::VARIABLE => Some(1),
5640 lsp::CompletionItemKind::CONSTANT => Some(2),
5641 lsp::CompletionItemKind::PROPERTY => Some(3),
5642 _ => None,
5643 })
5644 .unwrap_or(DEFAULT_KIND_KEY);
5645 (kind_key, self.label.filter_text())
5646 }
5647
5648 /// Whether this completion is a snippet.
5649 pub fn is_snippet(&self) -> bool {
5650 self.source
5651 // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5652 .lsp_completion(true)
5653 .is_some_and(|lsp_completion| {
5654 lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5655 })
5656 }
5657
5658 /// Returns the corresponding color for this completion.
5659 ///
5660 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5661 pub fn color(&self) -> Option<Hsla> {
5662 // `lsp::CompletionListItemDefaults` has no `kind` field
5663 let lsp_completion = self.source.lsp_completion(false)?;
5664 if lsp_completion.kind? == CompletionItemKind::COLOR {
5665 return color_extractor::extract_color(&lsp_completion);
5666 }
5667 None
5668 }
5669}
5670
5671fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5672 match level {
5673 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5674 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5675 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5676 }
5677}
5678
5679fn provide_inline_values(
5680 captures: impl Iterator<Item = (Range<usize>, language::DebuggerTextObject)>,
5681 snapshot: &language::BufferSnapshot,
5682 max_row: usize,
5683) -> Vec<InlineValueLocation> {
5684 let mut variables = Vec::new();
5685 let mut variable_position = HashSet::default();
5686 let mut scopes = Vec::new();
5687
5688 let active_debug_line_offset = snapshot.point_to_offset(Point::new(max_row as u32, 0));
5689
5690 for (capture_range, capture_kind) in captures {
5691 match capture_kind {
5692 language::DebuggerTextObject::Variable => {
5693 let variable_name = snapshot
5694 .text_for_range(capture_range.clone())
5695 .collect::<String>();
5696 let point = snapshot.offset_to_point(capture_range.end);
5697
5698 while scopes
5699 .last()
5700 .is_some_and(|scope: &Range<_>| !scope.contains(&capture_range.start))
5701 {
5702 scopes.pop();
5703 }
5704
5705 if point.row as usize > max_row {
5706 break;
5707 }
5708
5709 let scope = if scopes
5710 .last()
5711 .is_none_or(|scope| !scope.contains(&active_debug_line_offset))
5712 {
5713 VariableScope::Global
5714 } else {
5715 VariableScope::Local
5716 };
5717
5718 if variable_position.insert(capture_range.end) {
5719 variables.push(InlineValueLocation {
5720 variable_name,
5721 scope,
5722 lookup: VariableLookupKind::Variable,
5723 row: point.row as usize,
5724 column: point.column as usize,
5725 });
5726 }
5727 }
5728 language::DebuggerTextObject::Scope => {
5729 while scopes.last().map_or_else(
5730 || false,
5731 |scope: &Range<usize>| {
5732 !(scope.contains(&capture_range.start)
5733 && scope.contains(&capture_range.end))
5734 },
5735 ) {
5736 scopes.pop();
5737 }
5738 scopes.push(capture_range);
5739 }
5740 }
5741 }
5742
5743 variables
5744}
5745
5746#[cfg(test)]
5747mod disable_ai_settings_tests {
5748 use super::*;
5749 use gpui::TestAppContext;
5750 use settings::Settings;
5751
5752 #[gpui::test]
5753 async fn test_disable_ai_settings_security(cx: &mut TestAppContext) {
5754 cx.update(|cx| {
5755 settings::init(cx);
5756 Project::init_settings(cx);
5757
5758 // Test 1: Default is false (AI enabled)
5759 assert!(
5760 !DisableAiSettings::get_global(cx).disable_ai,
5761 "Default should allow AI"
5762 );
5763 });
5764
5765 let disable_true = serde_json::json!({
5766 "disable_ai": true
5767 })
5768 .to_string();
5769 let disable_false = serde_json::json!({
5770 "disable_ai": false
5771 })
5772 .to_string();
5773
5774 cx.update_global::<SettingsStore, _>(|store, cx| {
5775 store.set_user_settings(&disable_false, cx).unwrap();
5776 store.set_global_settings(&disable_true, cx).unwrap();
5777 });
5778 cx.update(|cx| {
5779 assert!(
5780 DisableAiSettings::get_global(cx).disable_ai,
5781 "Local false cannot override global true"
5782 );
5783 });
5784
5785 cx.update_global::<SettingsStore, _>(|store, cx| {
5786 store.set_global_settings(&disable_false, cx).unwrap();
5787 store.set_user_settings(&disable_true, cx).unwrap();
5788 });
5789
5790 cx.update(|cx| {
5791 assert!(
5792 DisableAiSettings::get_global(cx).disable_ai,
5793 "Local false cannot override global true"
5794 );
5795 });
5796 }
5797}