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