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