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