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