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 self.lsp_store
3806 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3807 }
3808
3809 pub fn linked_edits(
3810 &self,
3811 buffer: &Entity<Buffer>,
3812 position: Anchor,
3813 cx: &mut Context<Self>,
3814 ) -> Task<Result<Vec<Range<Anchor>>>> {
3815 self.lsp_store.update(cx, |lsp_store, cx| {
3816 lsp_store.linked_edits(buffer, position, cx)
3817 })
3818 }
3819
3820 pub fn completions<T: ToOffset + ToPointUtf16>(
3821 &self,
3822 buffer: &Entity<Buffer>,
3823 position: T,
3824 context: CompletionContext,
3825 cx: &mut Context<Self>,
3826 ) -> Task<Result<Vec<CompletionResponse>>> {
3827 let position = position.to_point_utf16(buffer.read(cx));
3828 self.lsp_store.update(cx, |lsp_store, cx| {
3829 lsp_store.completions(buffer, position, context, cx)
3830 })
3831 }
3832
3833 pub fn code_actions<T: Clone + ToOffset>(
3834 &mut self,
3835 buffer_handle: &Entity<Buffer>,
3836 range: Range<T>,
3837 kinds: Option<Vec<CodeActionKind>>,
3838 cx: &mut Context<Self>,
3839 ) -> Task<Result<Option<Vec<CodeAction>>>> {
3840 let buffer = buffer_handle.read(cx);
3841 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3842 self.lsp_store.update(cx, |lsp_store, cx| {
3843 lsp_store.code_actions(buffer_handle, range, kinds, cx)
3844 })
3845 }
3846
3847 pub fn code_lens_actions<T: Clone + ToOffset>(
3848 &mut self,
3849 buffer: &Entity<Buffer>,
3850 range: Range<T>,
3851 cx: &mut Context<Self>,
3852 ) -> Task<Result<Option<Vec<CodeAction>>>> {
3853 let snapshot = buffer.read(cx).snapshot();
3854 let range = range.to_point(&snapshot);
3855 let range_start = snapshot.anchor_before(range.start);
3856 let range_end = if range.start == range.end {
3857 range_start
3858 } else {
3859 snapshot.anchor_after(range.end)
3860 };
3861 let range = range_start..range_end;
3862 let code_lens_actions = self
3863 .lsp_store
3864 .update(cx, |lsp_store, cx| lsp_store.code_lens_actions(buffer, cx));
3865
3866 cx.background_spawn(async move {
3867 let mut code_lens_actions = code_lens_actions
3868 .await
3869 .map_err(|e| anyhow!("code lens fetch failed: {e:#}"))?;
3870 if let Some(code_lens_actions) = &mut code_lens_actions {
3871 code_lens_actions.retain(|code_lens_action| {
3872 range
3873 .start
3874 .cmp(&code_lens_action.range.start, &snapshot)
3875 .is_ge()
3876 && range
3877 .end
3878 .cmp(&code_lens_action.range.end, &snapshot)
3879 .is_le()
3880 });
3881 }
3882 Ok(code_lens_actions)
3883 })
3884 }
3885
3886 pub fn apply_code_action(
3887 &self,
3888 buffer_handle: Entity<Buffer>,
3889 action: CodeAction,
3890 push_to_history: bool,
3891 cx: &mut Context<Self>,
3892 ) -> Task<Result<ProjectTransaction>> {
3893 self.lsp_store.update(cx, |lsp_store, cx| {
3894 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3895 })
3896 }
3897
3898 pub fn apply_code_action_kind(
3899 &self,
3900 buffers: HashSet<Entity<Buffer>>,
3901 kind: CodeActionKind,
3902 push_to_history: bool,
3903 cx: &mut Context<Self>,
3904 ) -> Task<Result<ProjectTransaction>> {
3905 self.lsp_store.update(cx, |lsp_store, cx| {
3906 lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
3907 })
3908 }
3909
3910 pub fn prepare_rename<T: ToPointUtf16>(
3911 &mut self,
3912 buffer: Entity<Buffer>,
3913 position: T,
3914 cx: &mut Context<Self>,
3915 ) -> Task<Result<PrepareRenameResponse>> {
3916 let position = position.to_point_utf16(buffer.read(cx));
3917 self.request_lsp(
3918 buffer,
3919 LanguageServerToQuery::FirstCapable,
3920 PrepareRename { position },
3921 cx,
3922 )
3923 }
3924
3925 pub fn perform_rename<T: ToPointUtf16>(
3926 &mut self,
3927 buffer: Entity<Buffer>,
3928 position: T,
3929 new_name: String,
3930 cx: &mut Context<Self>,
3931 ) -> Task<Result<ProjectTransaction>> {
3932 let push_to_history = true;
3933 let position = position.to_point_utf16(buffer.read(cx));
3934 self.request_lsp(
3935 buffer,
3936 LanguageServerToQuery::FirstCapable,
3937 PerformRename {
3938 position,
3939 new_name,
3940 push_to_history,
3941 },
3942 cx,
3943 )
3944 }
3945
3946 pub fn on_type_format<T: ToPointUtf16>(
3947 &mut self,
3948 buffer: Entity<Buffer>,
3949 position: T,
3950 trigger: String,
3951 push_to_history: bool,
3952 cx: &mut Context<Self>,
3953 ) -> Task<Result<Option<Transaction>>> {
3954 self.lsp_store.update(cx, |lsp_store, cx| {
3955 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3956 })
3957 }
3958
3959 pub fn inline_values(
3960 &mut self,
3961 session: Entity<Session>,
3962 active_stack_frame: ActiveStackFrame,
3963 buffer_handle: Entity<Buffer>,
3964 range: Range<text::Anchor>,
3965 cx: &mut Context<Self>,
3966 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3967 let snapshot = buffer_handle.read(cx).snapshot();
3968
3969 let captures = snapshot.debug_variables_query(Anchor::MIN..range.end);
3970
3971 let row = snapshot
3972 .summary_for_anchor::<text::PointUtf16>(&range.end)
3973 .row as usize;
3974
3975 let inline_value_locations = provide_inline_values(captures, &snapshot, row);
3976
3977 let stack_frame_id = active_stack_frame.stack_frame_id;
3978 cx.spawn(async move |this, cx| {
3979 this.update(cx, |project, cx| {
3980 project.dap_store().update(cx, |dap_store, cx| {
3981 dap_store.resolve_inline_value_locations(
3982 session,
3983 stack_frame_id,
3984 buffer_handle,
3985 inline_value_locations,
3986 cx,
3987 )
3988 })
3989 })?
3990 .await
3991 })
3992 }
3993
3994 pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
3995 let (result_tx, result_rx) = smol::channel::unbounded();
3996
3997 let matching_buffers_rx = if query.is_opened_only() {
3998 self.sort_search_candidates(&query, cx)
3999 } else {
4000 self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
4001 };
4002
4003 cx.spawn(async move |_, cx| {
4004 let mut range_count = 0;
4005 let mut buffer_count = 0;
4006 let mut limit_reached = false;
4007 let query = Arc::new(query);
4008 let chunks = matching_buffers_rx.ready_chunks(64);
4009
4010 // Now that we know what paths match the query, we will load at most
4011 // 64 buffers at a time to avoid overwhelming the main thread. For each
4012 // opened buffer, we will spawn a background task that retrieves all the
4013 // ranges in the buffer matched by the query.
4014 let mut chunks = pin!(chunks);
4015 'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
4016 let mut chunk_results = Vec::with_capacity(matching_buffer_chunk.len());
4017 for buffer in matching_buffer_chunk {
4018 let query = query.clone();
4019 let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot())?;
4020 chunk_results.push(cx.background_spawn(async move {
4021 let ranges = query
4022 .search(&snapshot, None)
4023 .await
4024 .iter()
4025 .map(|range| {
4026 snapshot.anchor_before(range.start)
4027 ..snapshot.anchor_after(range.end)
4028 })
4029 .collect::<Vec<_>>();
4030 anyhow::Ok((buffer, ranges))
4031 }));
4032 }
4033
4034 let chunk_results = futures::future::join_all(chunk_results).await;
4035 for result in chunk_results {
4036 if let Some((buffer, ranges)) = result.log_err() {
4037 range_count += ranges.len();
4038 buffer_count += 1;
4039 result_tx
4040 .send(SearchResult::Buffer { buffer, ranges })
4041 .await?;
4042 if buffer_count > MAX_SEARCH_RESULT_FILES
4043 || range_count > MAX_SEARCH_RESULT_RANGES
4044 {
4045 limit_reached = true;
4046 break 'outer;
4047 }
4048 }
4049 }
4050 }
4051
4052 if limit_reached {
4053 result_tx.send(SearchResult::LimitReached).await?;
4054 }
4055
4056 anyhow::Ok(())
4057 })
4058 .detach();
4059
4060 result_rx
4061 }
4062
4063 pub fn find_search_candidate_buffers(
4064 &mut self,
4065 query: &SearchQuery,
4066 limit: usize,
4067 cx: &mut Context<Project>,
4068 ) -> Receiver<Entity<Buffer>> {
4069 if self.is_local() {
4070 let fs = self.fs.clone();
4071 self.buffer_store.update(cx, |buffer_store, cx| {
4072 buffer_store.find_search_candidates(query, limit, fs, cx)
4073 })
4074 } else {
4075 self.find_search_candidates_remote(query, limit, cx)
4076 }
4077 }
4078
4079 fn sort_search_candidates(
4080 &mut self,
4081 search_query: &SearchQuery,
4082 cx: &mut Context<Project>,
4083 ) -> Receiver<Entity<Buffer>> {
4084 let worktree_store = self.worktree_store.read(cx);
4085 let mut buffers = search_query
4086 .buffers()
4087 .into_iter()
4088 .flatten()
4089 .filter(|buffer| {
4090 let b = buffer.read(cx);
4091 if let Some(file) = b.file() {
4092 if !search_query.match_path(file.path().as_std_path()) {
4093 return false;
4094 }
4095 if let Some(entry) = b
4096 .entry_id(cx)
4097 .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
4098 && entry.is_ignored
4099 && !search_query.include_ignored()
4100 {
4101 return false;
4102 }
4103 }
4104 true
4105 })
4106 .collect::<Vec<_>>();
4107 let (tx, rx) = smol::channel::unbounded();
4108 buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
4109 (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
4110 (None, Some(_)) => std::cmp::Ordering::Less,
4111 (Some(_), None) => std::cmp::Ordering::Greater,
4112 (Some(a), Some(b)) => compare_paths(
4113 (a.path().as_std_path(), true),
4114 (b.path().as_std_path(), true),
4115 ),
4116 });
4117 for buffer in buffers {
4118 tx.send_blocking(buffer.clone()).unwrap()
4119 }
4120
4121 rx
4122 }
4123
4124 fn find_search_candidates_remote(
4125 &mut self,
4126 query: &SearchQuery,
4127 limit: usize,
4128 cx: &mut Context<Project>,
4129 ) -> Receiver<Entity<Buffer>> {
4130 let (tx, rx) = smol::channel::unbounded();
4131
4132 let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.remote_client
4133 {
4134 (ssh_client.read(cx).proto_client(), 0)
4135 } else if let Some(remote_id) = self.remote_id() {
4136 (self.collab_client.clone().into(), remote_id)
4137 } else {
4138 return rx;
4139 };
4140
4141 let request = client.request(proto::FindSearchCandidates {
4142 project_id: remote_id,
4143 query: Some(query.to_proto()),
4144 limit: limit as _,
4145 });
4146 let guard = self.retain_remotely_created_models(cx);
4147
4148 cx.spawn(async move |project, cx| {
4149 let response = request.await?;
4150 for buffer_id in response.buffer_ids {
4151 let buffer_id = BufferId::new(buffer_id)?;
4152 let buffer = project
4153 .update(cx, |project, cx| {
4154 project.buffer_store.update(cx, |buffer_store, cx| {
4155 buffer_store.wait_for_remote_buffer(buffer_id, cx)
4156 })
4157 })?
4158 .await?;
4159 let _ = tx.send(buffer).await;
4160 }
4161
4162 drop(guard);
4163 anyhow::Ok(())
4164 })
4165 .detach_and_log_err(cx);
4166 rx
4167 }
4168
4169 pub fn request_lsp<R: LspCommand>(
4170 &mut self,
4171 buffer_handle: Entity<Buffer>,
4172 server: LanguageServerToQuery,
4173 request: R,
4174 cx: &mut Context<Self>,
4175 ) -> Task<Result<R::Response>>
4176 where
4177 <R::LspRequest as lsp::request::Request>::Result: Send,
4178 <R::LspRequest as lsp::request::Request>::Params: Send,
4179 {
4180 let guard = self.retain_remotely_created_models(cx);
4181 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4182 lsp_store.request_lsp(buffer_handle, server, request, cx)
4183 });
4184 cx.background_spawn(async move {
4185 let result = task.await;
4186 drop(guard);
4187 result
4188 })
4189 }
4190
4191 /// Move a worktree to a new position in the worktree order.
4192 ///
4193 /// The worktree will moved to the opposite side of the destination worktree.
4194 ///
4195 /// # Example
4196 ///
4197 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
4198 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
4199 ///
4200 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
4201 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
4202 ///
4203 /// # Errors
4204 ///
4205 /// An error will be returned if the worktree or destination worktree are not found.
4206 pub fn move_worktree(
4207 &mut self,
4208 source: WorktreeId,
4209 destination: WorktreeId,
4210 cx: &mut Context<Self>,
4211 ) -> Result<()> {
4212 self.worktree_store.update(cx, |worktree_store, cx| {
4213 worktree_store.move_worktree(source, destination, cx)
4214 })
4215 }
4216
4217 pub fn find_or_create_worktree(
4218 &mut self,
4219 abs_path: impl AsRef<Path>,
4220 visible: bool,
4221 cx: &mut Context<Self>,
4222 ) -> Task<Result<(Entity<Worktree>, Arc<RelPath>)>> {
4223 self.worktree_store.update(cx, |worktree_store, cx| {
4224 worktree_store.find_or_create_worktree(abs_path, visible, cx)
4225 })
4226 }
4227
4228 pub fn find_worktree(
4229 &self,
4230 abs_path: &Path,
4231 cx: &App,
4232 ) -> Option<(Entity<Worktree>, Arc<RelPath>)> {
4233 self.worktree_store.read(cx).find_worktree(abs_path, cx)
4234 }
4235
4236 pub fn is_shared(&self) -> bool {
4237 match &self.client_state {
4238 ProjectClientState::Shared { .. } => true,
4239 ProjectClientState::Local => false,
4240 ProjectClientState::Remote { .. } => true,
4241 }
4242 }
4243
4244 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
4245 pub fn resolve_path_in_buffer(
4246 &self,
4247 path: &str,
4248 buffer: &Entity<Buffer>,
4249 cx: &mut Context<Self>,
4250 ) -> Task<Option<ResolvedPath>> {
4251 if util::paths::is_absolute(path, self.path_style(cx)) || path.starts_with("~") {
4252 self.resolve_abs_path(path, cx)
4253 } else {
4254 self.resolve_path_in_worktrees(path, buffer, cx)
4255 }
4256 }
4257
4258 pub fn resolve_abs_file_path(
4259 &self,
4260 path: &str,
4261 cx: &mut Context<Self>,
4262 ) -> Task<Option<ResolvedPath>> {
4263 let resolve_task = self.resolve_abs_path(path, cx);
4264 cx.background_spawn(async move {
4265 let resolved_path = resolve_task.await;
4266 resolved_path.filter(|path| path.is_file())
4267 })
4268 }
4269
4270 pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
4271 if self.is_local() {
4272 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
4273 let fs = self.fs.clone();
4274 cx.background_spawn(async move {
4275 let metadata = fs.metadata(&expanded).await.ok().flatten();
4276
4277 metadata.map(|metadata| ResolvedPath::AbsPath {
4278 path: expanded.to_string_lossy().into_owned(),
4279 is_dir: metadata.is_dir,
4280 })
4281 })
4282 } else if let Some(ssh_client) = self.remote_client.as_ref() {
4283 let request = ssh_client
4284 .read(cx)
4285 .proto_client()
4286 .request(proto::GetPathMetadata {
4287 project_id: REMOTE_SERVER_PROJECT_ID,
4288 path: path.into(),
4289 });
4290 cx.background_spawn(async move {
4291 let response = request.await.log_err()?;
4292 if response.exists {
4293 Some(ResolvedPath::AbsPath {
4294 path: response.path,
4295 is_dir: response.is_dir,
4296 })
4297 } else {
4298 None
4299 }
4300 })
4301 } else {
4302 Task::ready(None)
4303 }
4304 }
4305
4306 fn resolve_path_in_worktrees(
4307 &self,
4308 path: &str,
4309 buffer: &Entity<Buffer>,
4310 cx: &mut Context<Self>,
4311 ) -> Task<Option<ResolvedPath>> {
4312 let mut candidates = vec![];
4313 let path_style = self.path_style(cx);
4314 if let Ok(path) = RelPath::new(path.as_ref(), path_style) {
4315 candidates.push(path.into_arc());
4316 }
4317
4318 if let Some(file) = buffer.read(cx).file()
4319 && let Some(dir) = file.path().parent()
4320 {
4321 if let Some(joined) = path_style.join(&*dir.display(path_style), path)
4322 && let Some(joined) = RelPath::new(joined.as_ref(), path_style).ok()
4323 {
4324 candidates.push(joined.into_arc());
4325 }
4326 }
4327
4328 let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
4329 let worktrees_with_ids: Vec<_> = self
4330 .worktrees(cx)
4331 .map(|worktree| {
4332 let id = worktree.read(cx).id();
4333 (worktree, id)
4334 })
4335 .collect();
4336
4337 cx.spawn(async move |_, cx| {
4338 if let Some(buffer_worktree_id) = buffer_worktree_id
4339 && let Some((worktree, _)) = worktrees_with_ids
4340 .iter()
4341 .find(|(_, id)| *id == buffer_worktree_id)
4342 {
4343 for candidate in candidates.iter() {
4344 if let Some(path) = Self::resolve_path_in_worktree(worktree, candidate, cx) {
4345 return Some(path);
4346 }
4347 }
4348 }
4349 for (worktree, id) in worktrees_with_ids {
4350 if Some(id) == buffer_worktree_id {
4351 continue;
4352 }
4353 for candidate in candidates.iter() {
4354 if let Some(path) = Self::resolve_path_in_worktree(&worktree, candidate, cx) {
4355 return Some(path);
4356 }
4357 }
4358 }
4359 None
4360 })
4361 }
4362
4363 fn resolve_path_in_worktree(
4364 worktree: &Entity<Worktree>,
4365 path: &RelPath,
4366 cx: &mut AsyncApp,
4367 ) -> Option<ResolvedPath> {
4368 worktree
4369 .read_with(cx, |worktree, _| {
4370 worktree.entry_for_path(path).map(|entry| {
4371 let project_path = ProjectPath {
4372 worktree_id: worktree.id(),
4373 path: entry.path.clone(),
4374 };
4375 ResolvedPath::ProjectPath {
4376 project_path,
4377 is_dir: entry.is_dir(),
4378 }
4379 })
4380 })
4381 .ok()?
4382 }
4383
4384 pub fn list_directory(
4385 &self,
4386 query: String,
4387 cx: &mut Context<Self>,
4388 ) -> Task<Result<Vec<DirectoryItem>>> {
4389 if self.is_local() {
4390 DirectoryLister::Local(cx.entity(), self.fs.clone()).list_directory(query, cx)
4391 } else if let Some(session) = self.remote_client.as_ref() {
4392 let request = proto::ListRemoteDirectory {
4393 dev_server_id: REMOTE_SERVER_PROJECT_ID,
4394 path: query,
4395 config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4396 };
4397
4398 let response = session.read(cx).proto_client().request(request);
4399 cx.background_spawn(async move {
4400 let proto::ListRemoteDirectoryResponse {
4401 entries,
4402 entry_info,
4403 } = response.await?;
4404 Ok(entries
4405 .into_iter()
4406 .zip(entry_info)
4407 .map(|(entry, info)| DirectoryItem {
4408 path: PathBuf::from(entry),
4409 is_dir: info.is_dir,
4410 })
4411 .collect())
4412 })
4413 } else {
4414 Task::ready(Err(anyhow!("cannot list directory in remote project")))
4415 }
4416 }
4417
4418 pub fn create_worktree(
4419 &mut self,
4420 abs_path: impl AsRef<Path>,
4421 visible: bool,
4422 cx: &mut Context<Self>,
4423 ) -> Task<Result<Entity<Worktree>>> {
4424 self.worktree_store.update(cx, |worktree_store, cx| {
4425 worktree_store.create_worktree(abs_path, visible, cx)
4426 })
4427 }
4428
4429 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4430 self.worktree_store.update(cx, |worktree_store, cx| {
4431 worktree_store.remove_worktree(id_to_remove, cx);
4432 });
4433 }
4434
4435 fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4436 self.worktree_store.update(cx, |worktree_store, cx| {
4437 worktree_store.add(worktree, cx);
4438 });
4439 }
4440
4441 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4442 let new_active_entry = entry.and_then(|project_path| {
4443 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4444 let entry = worktree.read(cx).entry_for_path(&project_path.path)?;
4445 Some(entry.id)
4446 });
4447 if new_active_entry != self.active_entry {
4448 self.active_entry = new_active_entry;
4449 self.lsp_store.update(cx, |lsp_store, _| {
4450 lsp_store.set_active_entry(new_active_entry);
4451 });
4452 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4453 }
4454 }
4455
4456 pub fn language_servers_running_disk_based_diagnostics<'a>(
4457 &'a self,
4458 cx: &'a App,
4459 ) -> impl Iterator<Item = LanguageServerId> + 'a {
4460 self.lsp_store
4461 .read(cx)
4462 .language_servers_running_disk_based_diagnostics()
4463 }
4464
4465 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4466 self.lsp_store
4467 .read(cx)
4468 .diagnostic_summary(include_ignored, cx)
4469 }
4470
4471 /// Returns a summary of the diagnostics for the provided project path only.
4472 pub fn diagnostic_summary_for_path(&self, path: &ProjectPath, cx: &App) -> DiagnosticSummary {
4473 self.lsp_store
4474 .read(cx)
4475 .diagnostic_summary_for_path(path, cx)
4476 }
4477
4478 pub fn diagnostic_summaries<'a>(
4479 &'a self,
4480 include_ignored: bool,
4481 cx: &'a App,
4482 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4483 self.lsp_store
4484 .read(cx)
4485 .diagnostic_summaries(include_ignored, cx)
4486 }
4487
4488 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4489 self.active_entry
4490 }
4491
4492 pub fn entry_for_path<'a>(&'a self, path: &ProjectPath, cx: &'a App) -> Option<&'a Entry> {
4493 self.worktree_store.read(cx).entry_for_path(path, cx)
4494 }
4495
4496 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4497 let worktree = self.worktree_for_entry(entry_id, cx)?;
4498 let worktree = worktree.read(cx);
4499 let worktree_id = worktree.id();
4500 let path = worktree.entry_for_id(entry_id)?.path.clone();
4501 Some(ProjectPath { worktree_id, path })
4502 }
4503
4504 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4505 Some(
4506 self.worktree_for_id(project_path.worktree_id, cx)?
4507 .read(cx)
4508 .absolutize(&project_path.path),
4509 )
4510 }
4511
4512 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4513 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4514 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4515 /// the first visible worktree that has an entry for that relative path.
4516 ///
4517 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4518 /// root name from paths.
4519 ///
4520 /// # Arguments
4521 ///
4522 /// * `path` - An absolute path, or a full path that starts with a worktree root name, or a
4523 /// relative path within a visible worktree.
4524 /// * `cx` - A reference to the `AppContext`.
4525 ///
4526 /// # Returns
4527 ///
4528 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4529 pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4530 let path_style = self.path_style(cx);
4531 let path = path.as_ref();
4532 let worktree_store = self.worktree_store.read(cx);
4533
4534 if is_absolute(&path.to_string_lossy(), path_style) {
4535 for worktree in worktree_store.visible_worktrees(cx) {
4536 let worktree_abs_path = worktree.read(cx).abs_path();
4537
4538 if let Ok(relative_path) = path.strip_prefix(worktree_abs_path)
4539 && let Ok(path) = RelPath::new(relative_path, path_style)
4540 {
4541 return Some(ProjectPath {
4542 worktree_id: worktree.read(cx).id(),
4543 path: path.into_arc(),
4544 });
4545 }
4546 }
4547 } else {
4548 for worktree in worktree_store.visible_worktrees(cx) {
4549 let worktree_root_name = worktree.read(cx).root_name();
4550 if let Ok(relative_path) = path.strip_prefix(worktree_root_name.as_std_path())
4551 && let Ok(path) = RelPath::new(relative_path, path_style)
4552 {
4553 return Some(ProjectPath {
4554 worktree_id: worktree.read(cx).id(),
4555 path: path.into_arc(),
4556 });
4557 }
4558 }
4559
4560 for worktree in worktree_store.visible_worktrees(cx) {
4561 let worktree = worktree.read(cx);
4562 if let Ok(path) = RelPath::new(path, path_style)
4563 && let Some(entry) = worktree.entry_for_path(&path)
4564 {
4565 return Some(ProjectPath {
4566 worktree_id: worktree.id(),
4567 path: entry.path.clone(),
4568 });
4569 }
4570 }
4571 }
4572
4573 None
4574 }
4575
4576 /// If there's only one visible worktree, returns the given worktree-relative path with no prefix.
4577 ///
4578 /// Otherwise, returns the full path for the project path (obtained by prefixing the worktree-relative path with the name of the worktree).
4579 pub fn short_full_path_for_project_path(
4580 &self,
4581 project_path: &ProjectPath,
4582 cx: &App,
4583 ) -> Option<String> {
4584 let path_style = self.path_style(cx);
4585 if self.visible_worktrees(cx).take(2).count() < 2 {
4586 return Some(project_path.path.display(path_style).to_string());
4587 }
4588 self.worktree_for_id(project_path.worktree_id, cx)
4589 .map(|worktree| {
4590 let worktree_name = worktree.read(cx).root_name();
4591 worktree_name
4592 .join(&project_path.path)
4593 .display(path_style)
4594 .to_string()
4595 })
4596 }
4597
4598 pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4599 self.find_worktree(abs_path, cx)
4600 .map(|(worktree, relative_path)| ProjectPath {
4601 worktree_id: worktree.read(cx).id(),
4602 path: relative_path,
4603 })
4604 }
4605
4606 pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4607 Some(
4608 self.worktree_for_id(project_path.worktree_id, cx)?
4609 .read(cx)
4610 .abs_path()
4611 .to_path_buf(),
4612 )
4613 }
4614
4615 pub fn blame_buffer(
4616 &self,
4617 buffer: &Entity<Buffer>,
4618 version: Option<clock::Global>,
4619 cx: &mut App,
4620 ) -> Task<Result<Option<Blame>>> {
4621 self.git_store.update(cx, |git_store, cx| {
4622 git_store.blame_buffer(buffer, version, cx)
4623 })
4624 }
4625
4626 pub fn get_permalink_to_line(
4627 &self,
4628 buffer: &Entity<Buffer>,
4629 selection: Range<u32>,
4630 cx: &mut App,
4631 ) -> Task<Result<url::Url>> {
4632 self.git_store.update(cx, |git_store, cx| {
4633 git_store.get_permalink_to_line(buffer, selection, cx)
4634 })
4635 }
4636
4637 // RPC message handlers
4638
4639 async fn handle_unshare_project(
4640 this: Entity<Self>,
4641 _: TypedEnvelope<proto::UnshareProject>,
4642 mut cx: AsyncApp,
4643 ) -> Result<()> {
4644 this.update(&mut cx, |this, cx| {
4645 if this.is_local() || this.is_via_remote_server() {
4646 this.unshare(cx)?;
4647 } else {
4648 this.disconnected_from_host(cx);
4649 }
4650 Ok(())
4651 })?
4652 }
4653
4654 async fn handle_add_collaborator(
4655 this: Entity<Self>,
4656 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4657 mut cx: AsyncApp,
4658 ) -> Result<()> {
4659 let collaborator = envelope
4660 .payload
4661 .collaborator
4662 .take()
4663 .context("empty collaborator")?;
4664
4665 let collaborator = Collaborator::from_proto(collaborator)?;
4666 this.update(&mut cx, |this, cx| {
4667 this.buffer_store.update(cx, |buffer_store, _| {
4668 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4669 });
4670 this.breakpoint_store.read(cx).broadcast();
4671 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4672 this.collaborators
4673 .insert(collaborator.peer_id, collaborator);
4674 })?;
4675
4676 Ok(())
4677 }
4678
4679 async fn handle_update_project_collaborator(
4680 this: Entity<Self>,
4681 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4682 mut cx: AsyncApp,
4683 ) -> Result<()> {
4684 let old_peer_id = envelope
4685 .payload
4686 .old_peer_id
4687 .context("missing old peer id")?;
4688 let new_peer_id = envelope
4689 .payload
4690 .new_peer_id
4691 .context("missing new peer id")?;
4692 this.update(&mut cx, |this, cx| {
4693 let collaborator = this
4694 .collaborators
4695 .remove(&old_peer_id)
4696 .context("received UpdateProjectCollaborator for unknown peer")?;
4697 let is_host = collaborator.is_host;
4698 this.collaborators.insert(new_peer_id, collaborator);
4699
4700 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4701 this.buffer_store.update(cx, |buffer_store, _| {
4702 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4703 });
4704
4705 if is_host {
4706 this.buffer_store
4707 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4708 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4709 .unwrap();
4710 cx.emit(Event::HostReshared);
4711 }
4712
4713 cx.emit(Event::CollaboratorUpdated {
4714 old_peer_id,
4715 new_peer_id,
4716 });
4717 Ok(())
4718 })?
4719 }
4720
4721 async fn handle_remove_collaborator(
4722 this: Entity<Self>,
4723 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4724 mut cx: AsyncApp,
4725 ) -> Result<()> {
4726 this.update(&mut cx, |this, cx| {
4727 let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
4728 let replica_id = this
4729 .collaborators
4730 .remove(&peer_id)
4731 .with_context(|| format!("unknown peer {peer_id:?}"))?
4732 .replica_id;
4733 this.buffer_store.update(cx, |buffer_store, cx| {
4734 buffer_store.forget_shared_buffers_for(&peer_id);
4735 for buffer in buffer_store.buffers() {
4736 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4737 }
4738 });
4739 this.git_store.update(cx, |git_store, _| {
4740 git_store.forget_shared_diffs_for(&peer_id);
4741 });
4742
4743 cx.emit(Event::CollaboratorLeft(peer_id));
4744 Ok(())
4745 })?
4746 }
4747
4748 async fn handle_update_project(
4749 this: Entity<Self>,
4750 envelope: TypedEnvelope<proto::UpdateProject>,
4751 mut cx: AsyncApp,
4752 ) -> Result<()> {
4753 this.update(&mut cx, |this, cx| {
4754 // Don't handle messages that were sent before the response to us joining the project
4755 if envelope.message_id > this.join_project_response_message_id {
4756 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4757 }
4758 Ok(())
4759 })?
4760 }
4761
4762 async fn handle_toast(
4763 this: Entity<Self>,
4764 envelope: TypedEnvelope<proto::Toast>,
4765 mut cx: AsyncApp,
4766 ) -> Result<()> {
4767 this.update(&mut cx, |_, cx| {
4768 cx.emit(Event::Toast {
4769 notification_id: envelope.payload.notification_id.into(),
4770 message: envelope.payload.message,
4771 });
4772 Ok(())
4773 })?
4774 }
4775
4776 async fn handle_language_server_prompt_request(
4777 this: Entity<Self>,
4778 envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4779 mut cx: AsyncApp,
4780 ) -> Result<proto::LanguageServerPromptResponse> {
4781 let (tx, rx) = smol::channel::bounded(1);
4782 let actions: Vec<_> = envelope
4783 .payload
4784 .actions
4785 .into_iter()
4786 .map(|action| MessageActionItem {
4787 title: action,
4788 properties: Default::default(),
4789 })
4790 .collect();
4791 this.update(&mut cx, |_, cx| {
4792 cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4793 level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4794 message: envelope.payload.message,
4795 actions: actions.clone(),
4796 lsp_name: envelope.payload.lsp_name,
4797 response_channel: tx,
4798 }));
4799
4800 anyhow::Ok(())
4801 })??;
4802
4803 // We drop `this` to avoid holding a reference in this future for too
4804 // long.
4805 // If we keep the reference, we might not drop the `Project` early
4806 // enough when closing a window and it will only get releases on the
4807 // next `flush_effects()` call.
4808 drop(this);
4809
4810 let mut rx = pin!(rx);
4811 let answer = rx.next().await;
4812
4813 Ok(LanguageServerPromptResponse {
4814 action_response: answer.and_then(|answer| {
4815 actions
4816 .iter()
4817 .position(|action| *action == answer)
4818 .map(|index| index as u64)
4819 }),
4820 })
4821 }
4822
4823 async fn handle_hide_toast(
4824 this: Entity<Self>,
4825 envelope: TypedEnvelope<proto::HideToast>,
4826 mut cx: AsyncApp,
4827 ) -> Result<()> {
4828 this.update(&mut cx, |_, cx| {
4829 cx.emit(Event::HideToast {
4830 notification_id: envelope.payload.notification_id.into(),
4831 });
4832 Ok(())
4833 })?
4834 }
4835
4836 // Collab sends UpdateWorktree protos as messages
4837 async fn handle_update_worktree(
4838 this: Entity<Self>,
4839 envelope: TypedEnvelope<proto::UpdateWorktree>,
4840 mut cx: AsyncApp,
4841 ) -> Result<()> {
4842 this.update(&mut cx, |this, cx| {
4843 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4844 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4845 worktree.update(cx, |worktree, _| {
4846 let worktree = worktree.as_remote_mut().unwrap();
4847 worktree.update_from_remote(envelope.payload);
4848 });
4849 }
4850 Ok(())
4851 })?
4852 }
4853
4854 async fn handle_update_buffer_from_remote_server(
4855 this: Entity<Self>,
4856 envelope: TypedEnvelope<proto::UpdateBuffer>,
4857 cx: AsyncApp,
4858 ) -> Result<proto::Ack> {
4859 let buffer_store = this.read_with(&cx, |this, cx| {
4860 if let Some(remote_id) = this.remote_id() {
4861 let mut payload = envelope.payload.clone();
4862 payload.project_id = remote_id;
4863 cx.background_spawn(this.collab_client.request(payload))
4864 .detach_and_log_err(cx);
4865 }
4866 this.buffer_store.clone()
4867 })?;
4868 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4869 }
4870
4871 async fn handle_update_buffer(
4872 this: Entity<Self>,
4873 envelope: TypedEnvelope<proto::UpdateBuffer>,
4874 cx: AsyncApp,
4875 ) -> Result<proto::Ack> {
4876 let buffer_store = this.read_with(&cx, |this, cx| {
4877 if let Some(ssh) = &this.remote_client {
4878 let mut payload = envelope.payload.clone();
4879 payload.project_id = REMOTE_SERVER_PROJECT_ID;
4880 cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4881 .detach_and_log_err(cx);
4882 }
4883 this.buffer_store.clone()
4884 })?;
4885 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4886 }
4887
4888 fn retain_remotely_created_models(
4889 &mut self,
4890 cx: &mut Context<Self>,
4891 ) -> RemotelyCreatedModelGuard {
4892 {
4893 let mut remotely_create_models = self.remotely_created_models.lock();
4894 if remotely_create_models.retain_count == 0 {
4895 remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
4896 remotely_create_models.worktrees =
4897 self.worktree_store.read(cx).worktrees().collect();
4898 }
4899 remotely_create_models.retain_count += 1;
4900 }
4901 RemotelyCreatedModelGuard {
4902 remote_models: Arc::downgrade(&self.remotely_created_models),
4903 }
4904 }
4905
4906 async fn handle_create_buffer_for_peer(
4907 this: Entity<Self>,
4908 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4909 mut cx: AsyncApp,
4910 ) -> Result<()> {
4911 this.update(&mut cx, |this, cx| {
4912 this.buffer_store.update(cx, |buffer_store, cx| {
4913 buffer_store.handle_create_buffer_for_peer(
4914 envelope,
4915 this.replica_id(),
4916 this.capability(),
4917 cx,
4918 )
4919 })
4920 })?
4921 }
4922
4923 async fn handle_toggle_lsp_logs(
4924 project: Entity<Self>,
4925 envelope: TypedEnvelope<proto::ToggleLspLogs>,
4926 mut cx: AsyncApp,
4927 ) -> Result<()> {
4928 let toggled_log_kind =
4929 match proto::toggle_lsp_logs::LogType::from_i32(envelope.payload.log_type)
4930 .context("invalid log type")?
4931 {
4932 proto::toggle_lsp_logs::LogType::Log => LogKind::Logs,
4933 proto::toggle_lsp_logs::LogType::Trace => LogKind::Trace,
4934 proto::toggle_lsp_logs::LogType::Rpc => LogKind::Rpc,
4935 };
4936 project.update(&mut cx, |_, cx| {
4937 cx.emit(Event::ToggleLspLogs {
4938 server_id: LanguageServerId::from_proto(envelope.payload.server_id),
4939 enabled: envelope.payload.enabled,
4940 toggled_log_kind,
4941 })
4942 })?;
4943 Ok(())
4944 }
4945
4946 async fn handle_synchronize_buffers(
4947 this: Entity<Self>,
4948 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4949 mut cx: AsyncApp,
4950 ) -> Result<proto::SynchronizeBuffersResponse> {
4951 let response = this.update(&mut cx, |this, cx| {
4952 let client = this.collab_client.clone();
4953 this.buffer_store.update(cx, |this, cx| {
4954 this.handle_synchronize_buffers(envelope, cx, client)
4955 })
4956 })??;
4957
4958 Ok(response)
4959 }
4960
4961 async fn handle_search_candidate_buffers(
4962 this: Entity<Self>,
4963 envelope: TypedEnvelope<proto::FindSearchCandidates>,
4964 mut cx: AsyncApp,
4965 ) -> Result<proto::FindSearchCandidatesResponse> {
4966 let peer_id = envelope.original_sender_id()?;
4967 let message = envelope.payload;
4968 let path_style = this.read_with(&cx, |this, cx| this.path_style(cx))?;
4969 let query =
4970 SearchQuery::from_proto(message.query.context("missing query field")?, path_style)?;
4971 let results = this.update(&mut cx, |this, cx| {
4972 this.find_search_candidate_buffers(&query, message.limit as _, cx)
4973 })?;
4974
4975 let mut response = proto::FindSearchCandidatesResponse {
4976 buffer_ids: Vec::new(),
4977 };
4978
4979 while let Ok(buffer) = results.recv().await {
4980 this.update(&mut cx, |this, cx| {
4981 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4982 response.buffer_ids.push(buffer_id.to_proto());
4983 })?;
4984 }
4985
4986 Ok(response)
4987 }
4988
4989 async fn handle_open_buffer_by_id(
4990 this: Entity<Self>,
4991 envelope: TypedEnvelope<proto::OpenBufferById>,
4992 mut cx: AsyncApp,
4993 ) -> Result<proto::OpenBufferResponse> {
4994 let peer_id = envelope.original_sender_id()?;
4995 let buffer_id = BufferId::new(envelope.payload.id)?;
4996 let buffer = this
4997 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4998 .await?;
4999 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5000 }
5001
5002 async fn handle_open_buffer_by_path(
5003 this: Entity<Self>,
5004 envelope: TypedEnvelope<proto::OpenBufferByPath>,
5005 mut cx: AsyncApp,
5006 ) -> Result<proto::OpenBufferResponse> {
5007 let peer_id = envelope.original_sender_id()?;
5008 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5009 let path = RelPath::from_proto(&envelope.payload.path)?;
5010 let open_buffer = this
5011 .update(&mut cx, |this, cx| {
5012 this.open_buffer(ProjectPath { worktree_id, path }, cx)
5013 })?
5014 .await?;
5015 Project::respond_to_open_buffer_request(this, open_buffer, peer_id, &mut cx)
5016 }
5017
5018 async fn handle_open_new_buffer(
5019 this: Entity<Self>,
5020 envelope: TypedEnvelope<proto::OpenNewBuffer>,
5021 mut cx: AsyncApp,
5022 ) -> Result<proto::OpenBufferResponse> {
5023 let buffer = this
5024 .update(&mut cx, |this, cx| this.create_buffer(true, cx))?
5025 .await?;
5026 let peer_id = envelope.original_sender_id()?;
5027
5028 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5029 }
5030
5031 fn respond_to_open_buffer_request(
5032 this: Entity<Self>,
5033 buffer: Entity<Buffer>,
5034 peer_id: proto::PeerId,
5035 cx: &mut AsyncApp,
5036 ) -> Result<proto::OpenBufferResponse> {
5037 this.update(cx, |this, cx| {
5038 let is_private = buffer
5039 .read(cx)
5040 .file()
5041 .map(|f| f.is_private())
5042 .unwrap_or_default();
5043 anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
5044 Ok(proto::OpenBufferResponse {
5045 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
5046 })
5047 })?
5048 }
5049
5050 fn create_buffer_for_peer(
5051 &mut self,
5052 buffer: &Entity<Buffer>,
5053 peer_id: proto::PeerId,
5054 cx: &mut App,
5055 ) -> BufferId {
5056 self.buffer_store
5057 .update(cx, |buffer_store, cx| {
5058 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
5059 })
5060 .detach_and_log_err(cx);
5061 buffer.read(cx).remote_id()
5062 }
5063
5064 async fn handle_create_image_for_peer(
5065 this: Entity<Self>,
5066 envelope: TypedEnvelope<proto::CreateImageForPeer>,
5067 mut cx: AsyncApp,
5068 ) -> Result<()> {
5069 this.update(&mut cx, |this, cx| {
5070 this.image_store.update(cx, |image_store, cx| {
5071 image_store.handle_create_image_for_peer(envelope, cx)
5072 })
5073 })?
5074 .log_err();
5075 Ok(())
5076 }
5077
5078 fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
5079 let project_id = match self.client_state {
5080 ProjectClientState::Remote {
5081 sharing_has_stopped,
5082 remote_id,
5083 ..
5084 } => {
5085 if sharing_has_stopped {
5086 return Task::ready(Err(anyhow!(
5087 "can't synchronize remote buffers on a readonly project"
5088 )));
5089 } else {
5090 remote_id
5091 }
5092 }
5093 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
5094 return Task::ready(Err(anyhow!(
5095 "can't synchronize remote buffers on a local project"
5096 )));
5097 }
5098 };
5099
5100 let client = self.collab_client.clone();
5101 cx.spawn(async move |this, cx| {
5102 let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
5103 this.buffer_store.read(cx).buffer_version_info(cx)
5104 })?;
5105 let response = client
5106 .request(proto::SynchronizeBuffers {
5107 project_id,
5108 buffers,
5109 })
5110 .await?;
5111
5112 let send_updates_for_buffers = this.update(cx, |this, cx| {
5113 response
5114 .buffers
5115 .into_iter()
5116 .map(|buffer| {
5117 let client = client.clone();
5118 let buffer_id = match BufferId::new(buffer.id) {
5119 Ok(id) => id,
5120 Err(e) => {
5121 return Task::ready(Err(e));
5122 }
5123 };
5124 let remote_version = language::proto::deserialize_version(&buffer.version);
5125 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5126 let operations =
5127 buffer.read(cx).serialize_ops(Some(remote_version), cx);
5128 cx.background_spawn(async move {
5129 let operations = operations.await;
5130 for chunk in split_operations(operations) {
5131 client
5132 .request(proto::UpdateBuffer {
5133 project_id,
5134 buffer_id: buffer_id.into(),
5135 operations: chunk,
5136 })
5137 .await?;
5138 }
5139 anyhow::Ok(())
5140 })
5141 } else {
5142 Task::ready(Ok(()))
5143 }
5144 })
5145 .collect::<Vec<_>>()
5146 })?;
5147
5148 // Any incomplete buffers have open requests waiting. Request that the host sends
5149 // creates these buffers for us again to unblock any waiting futures.
5150 for id in incomplete_buffer_ids {
5151 cx.background_spawn(client.request(proto::OpenBufferById {
5152 project_id,
5153 id: id.into(),
5154 }))
5155 .detach();
5156 }
5157
5158 futures::future::join_all(send_updates_for_buffers)
5159 .await
5160 .into_iter()
5161 .collect()
5162 })
5163 }
5164
5165 pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
5166 self.worktree_store.read(cx).worktree_metadata_protos(cx)
5167 }
5168
5169 /// Iterator of all open buffers that have unsaved changes
5170 pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
5171 self.buffer_store.read(cx).buffers().filter_map(|buf| {
5172 let buf = buf.read(cx);
5173 if buf.is_dirty() {
5174 buf.project_path(cx)
5175 } else {
5176 None
5177 }
5178 })
5179 }
5180
5181 fn set_worktrees_from_proto(
5182 &mut self,
5183 worktrees: Vec<proto::WorktreeMetadata>,
5184 cx: &mut Context<Project>,
5185 ) -> Result<()> {
5186 self.worktree_store.update(cx, |worktree_store, cx| {
5187 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
5188 })
5189 }
5190
5191 fn set_collaborators_from_proto(
5192 &mut self,
5193 messages: Vec<proto::Collaborator>,
5194 cx: &mut Context<Self>,
5195 ) -> Result<()> {
5196 let mut collaborators = HashMap::default();
5197 for message in messages {
5198 let collaborator = Collaborator::from_proto(message)?;
5199 collaborators.insert(collaborator.peer_id, collaborator);
5200 }
5201 for old_peer_id in self.collaborators.keys() {
5202 if !collaborators.contains_key(old_peer_id) {
5203 cx.emit(Event::CollaboratorLeft(*old_peer_id));
5204 }
5205 }
5206 self.collaborators = collaborators;
5207 Ok(())
5208 }
5209
5210 pub fn supplementary_language_servers<'a>(
5211 &'a self,
5212 cx: &'a App,
5213 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
5214 self.lsp_store.read(cx).supplementary_language_servers()
5215 }
5216
5217 pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
5218 let Some(language) = buffer.language().cloned() else {
5219 return false;
5220 };
5221 self.lsp_store.update(cx, |lsp_store, _| {
5222 let relevant_language_servers = lsp_store
5223 .languages
5224 .lsp_adapters(&language.name())
5225 .into_iter()
5226 .map(|lsp_adapter| lsp_adapter.name())
5227 .collect::<HashSet<_>>();
5228 lsp_store
5229 .language_server_statuses()
5230 .filter_map(|(server_id, server_status)| {
5231 relevant_language_servers
5232 .contains(&server_status.name)
5233 .then_some(server_id)
5234 })
5235 .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5236 .any(InlayHints::check_capabilities)
5237 })
5238 }
5239
5240 pub fn language_server_id_for_name(
5241 &self,
5242 buffer: &Buffer,
5243 name: &LanguageServerName,
5244 cx: &App,
5245 ) -> Option<LanguageServerId> {
5246 let language = buffer.language()?;
5247 let relevant_language_servers = self
5248 .languages
5249 .lsp_adapters(&language.name())
5250 .into_iter()
5251 .map(|lsp_adapter| lsp_adapter.name())
5252 .collect::<HashSet<_>>();
5253 if !relevant_language_servers.contains(name) {
5254 return None;
5255 }
5256 self.language_server_statuses(cx)
5257 .filter(|(_, server_status)| relevant_language_servers.contains(&server_status.name))
5258 .find_map(|(server_id, server_status)| {
5259 if &server_status.name == name {
5260 Some(server_id)
5261 } else {
5262 None
5263 }
5264 })
5265 }
5266
5267 #[cfg(any(test, feature = "test-support"))]
5268 pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
5269 self.lsp_store.update(cx, |this, cx| {
5270 this.language_servers_for_local_buffer(buffer, cx)
5271 .next()
5272 .is_some()
5273 })
5274 }
5275
5276 pub fn git_init(
5277 &self,
5278 path: Arc<Path>,
5279 fallback_branch_name: String,
5280 cx: &App,
5281 ) -> Task<Result<()>> {
5282 self.git_store
5283 .read(cx)
5284 .git_init(path, fallback_branch_name, cx)
5285 }
5286
5287 pub fn buffer_store(&self) -> &Entity<BufferStore> {
5288 &self.buffer_store
5289 }
5290
5291 pub fn git_store(&self) -> &Entity<GitStore> {
5292 &self.git_store
5293 }
5294
5295 pub fn agent_server_store(&self) -> &Entity<AgentServerStore> {
5296 &self.agent_server_store
5297 }
5298
5299 #[cfg(test)]
5300 fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
5301 cx.spawn(async move |this, cx| {
5302 let scans_complete = this
5303 .read_with(cx, |this, cx| {
5304 this.worktrees(cx)
5305 .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
5306 .collect::<Vec<_>>()
5307 })
5308 .unwrap();
5309 join_all(scans_complete).await;
5310 let barriers = this
5311 .update(cx, |this, cx| {
5312 let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
5313 repos
5314 .into_iter()
5315 .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
5316 .collect::<Vec<_>>()
5317 })
5318 .unwrap();
5319 join_all(barriers).await;
5320 })
5321 }
5322
5323 pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
5324 self.git_store.read(cx).active_repository()
5325 }
5326
5327 pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
5328 self.git_store.read(cx).repositories()
5329 }
5330
5331 pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
5332 self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
5333 }
5334
5335 pub fn set_agent_location(
5336 &mut self,
5337 new_location: Option<AgentLocation>,
5338 cx: &mut Context<Self>,
5339 ) {
5340 if let Some(old_location) = self.agent_location.as_ref() {
5341 old_location
5342 .buffer
5343 .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
5344 .ok();
5345 }
5346
5347 if let Some(location) = new_location.as_ref() {
5348 location
5349 .buffer
5350 .update(cx, |buffer, cx| {
5351 buffer.set_agent_selections(
5352 Arc::from([language::Selection {
5353 id: 0,
5354 start: location.position,
5355 end: location.position,
5356 reversed: false,
5357 goal: language::SelectionGoal::None,
5358 }]),
5359 false,
5360 CursorShape::Hollow,
5361 cx,
5362 )
5363 })
5364 .ok();
5365 }
5366
5367 self.agent_location = new_location;
5368 cx.emit(Event::AgentLocationChanged);
5369 }
5370
5371 pub fn agent_location(&self) -> Option<AgentLocation> {
5372 self.agent_location.clone()
5373 }
5374
5375 pub fn path_style(&self, cx: &App) -> PathStyle {
5376 self.worktree_store.read(cx).path_style()
5377 }
5378
5379 pub fn contains_local_settings_file(
5380 &self,
5381 worktree_id: WorktreeId,
5382 rel_path: &RelPath,
5383 cx: &App,
5384 ) -> bool {
5385 self.worktree_for_id(worktree_id, cx)
5386 .map_or(false, |worktree| {
5387 worktree.read(cx).entry_for_path(rel_path).is_some()
5388 })
5389 }
5390
5391 pub fn update_local_settings_file(
5392 &self,
5393 worktree_id: WorktreeId,
5394 rel_path: Arc<RelPath>,
5395 cx: &mut App,
5396 update: impl 'static + Send + FnOnce(&mut settings::SettingsContent, &App),
5397 ) {
5398 let Some(worktree) = self.worktree_for_id(worktree_id, cx) else {
5399 // todo(settings_ui) error?
5400 return;
5401 };
5402 cx.spawn(async move |cx| {
5403 let file = worktree
5404 .update(cx, |worktree, cx| worktree.load_file(&rel_path, cx))?
5405 .await
5406 .context("Failed to load settings file")?;
5407
5408 let new_text = cx.read_global::<SettingsStore, _>(|store, cx| {
5409 store.new_text_for_update(file.text, move |settings| update(settings, cx))
5410 })?;
5411 worktree
5412 .update(cx, |worktree, cx| {
5413 let line_ending = text::LineEnding::detect(&new_text);
5414 worktree.write_file(rel_path.clone(), new_text.into(), line_ending, cx)
5415 })?
5416 .await
5417 .context("Failed to write settings file")?;
5418
5419 anyhow::Ok(())
5420 })
5421 .detach_and_log_err(cx);
5422 }
5423}
5424
5425pub struct PathMatchCandidateSet {
5426 pub snapshot: Snapshot,
5427 pub include_ignored: bool,
5428 pub include_root_name: bool,
5429 pub candidates: Candidates,
5430}
5431
5432pub enum Candidates {
5433 /// Only consider directories.
5434 Directories,
5435 /// Only consider files.
5436 Files,
5437 /// Consider directories and files.
5438 Entries,
5439}
5440
5441impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5442 type Candidates = PathMatchCandidateSetIter<'a>;
5443
5444 fn id(&self) -> usize {
5445 self.snapshot.id().to_usize()
5446 }
5447
5448 fn len(&self) -> usize {
5449 match self.candidates {
5450 Candidates::Files => {
5451 if self.include_ignored {
5452 self.snapshot.file_count()
5453 } else {
5454 self.snapshot.visible_file_count()
5455 }
5456 }
5457
5458 Candidates::Directories => {
5459 if self.include_ignored {
5460 self.snapshot.dir_count()
5461 } else {
5462 self.snapshot.visible_dir_count()
5463 }
5464 }
5465
5466 Candidates::Entries => {
5467 if self.include_ignored {
5468 self.snapshot.entry_count()
5469 } else {
5470 self.snapshot.visible_entry_count()
5471 }
5472 }
5473 }
5474 }
5475
5476 fn prefix(&self) -> Arc<RelPath> {
5477 if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
5478 self.snapshot.root_name().into()
5479 } else {
5480 RelPath::empty().into()
5481 }
5482 }
5483
5484 fn root_is_file(&self) -> bool {
5485 self.snapshot.root_entry().is_some_and(|f| f.is_file())
5486 }
5487
5488 fn path_style(&self) -> PathStyle {
5489 self.snapshot.path_style()
5490 }
5491
5492 fn candidates(&'a self, start: usize) -> Self::Candidates {
5493 PathMatchCandidateSetIter {
5494 traversal: match self.candidates {
5495 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5496 Candidates::Files => self.snapshot.files(self.include_ignored, start),
5497 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5498 },
5499 }
5500 }
5501}
5502
5503pub struct PathMatchCandidateSetIter<'a> {
5504 traversal: Traversal<'a>,
5505}
5506
5507impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5508 type Item = fuzzy::PathMatchCandidate<'a>;
5509
5510 fn next(&mut self) -> Option<Self::Item> {
5511 self.traversal
5512 .next()
5513 .map(|entry| fuzzy::PathMatchCandidate {
5514 is_dir: entry.kind.is_dir(),
5515 path: &entry.path,
5516 char_bag: entry.char_bag,
5517 })
5518 }
5519}
5520
5521impl EventEmitter<Event> for Project {}
5522
5523impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5524 fn from(val: &'a ProjectPath) -> Self {
5525 SettingsLocation {
5526 worktree_id: val.worktree_id,
5527 path: val.path.as_ref(),
5528 }
5529 }
5530}
5531
5532impl<P: Into<Arc<RelPath>>> From<(WorktreeId, P)> for ProjectPath {
5533 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5534 Self {
5535 worktree_id,
5536 path: path.into(),
5537 }
5538 }
5539}
5540
5541/// ResolvedPath is a path that has been resolved to either a ProjectPath
5542/// or an AbsPath and that *exists*.
5543#[derive(Debug, Clone)]
5544pub enum ResolvedPath {
5545 ProjectPath {
5546 project_path: ProjectPath,
5547 is_dir: bool,
5548 },
5549 AbsPath {
5550 path: String,
5551 is_dir: bool,
5552 },
5553}
5554
5555impl ResolvedPath {
5556 pub fn abs_path(&self) -> Option<&str> {
5557 match self {
5558 Self::AbsPath { path, .. } => Some(path),
5559 _ => None,
5560 }
5561 }
5562
5563 pub fn into_abs_path(self) -> Option<String> {
5564 match self {
5565 Self::AbsPath { path, .. } => Some(path),
5566 _ => None,
5567 }
5568 }
5569
5570 pub fn project_path(&self) -> Option<&ProjectPath> {
5571 match self {
5572 Self::ProjectPath { project_path, .. } => Some(project_path),
5573 _ => None,
5574 }
5575 }
5576
5577 pub fn is_file(&self) -> bool {
5578 !self.is_dir()
5579 }
5580
5581 pub fn is_dir(&self) -> bool {
5582 match self {
5583 Self::ProjectPath { is_dir, .. } => *is_dir,
5584 Self::AbsPath { is_dir, .. } => *is_dir,
5585 }
5586 }
5587}
5588
5589impl ProjectItem for Buffer {
5590 fn try_open(
5591 project: &Entity<Project>,
5592 path: &ProjectPath,
5593 cx: &mut App,
5594 ) -> Option<Task<Result<Entity<Self>>>> {
5595 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5596 }
5597
5598 fn entry_id(&self, _cx: &App) -> Option<ProjectEntryId> {
5599 File::from_dyn(self.file()).and_then(|file| file.project_entry_id())
5600 }
5601
5602 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5603 self.file().map(|file| ProjectPath {
5604 worktree_id: file.worktree_id(cx),
5605 path: file.path().clone(),
5606 })
5607 }
5608
5609 fn is_dirty(&self) -> bool {
5610 self.is_dirty()
5611 }
5612}
5613
5614impl Completion {
5615 pub fn kind(&self) -> Option<CompletionItemKind> {
5616 self.source
5617 // `lsp::CompletionListItemDefaults` has no `kind` field
5618 .lsp_completion(false)
5619 .and_then(|lsp_completion| lsp_completion.kind)
5620 }
5621
5622 pub fn label(&self) -> Option<String> {
5623 self.source
5624 .lsp_completion(false)
5625 .map(|lsp_completion| lsp_completion.label.clone())
5626 }
5627
5628 /// A key that can be used to sort completions when displaying
5629 /// them to the user.
5630 pub fn sort_key(&self) -> (usize, &str) {
5631 const DEFAULT_KIND_KEY: usize = 4;
5632 let kind_key = self
5633 .kind()
5634 .and_then(|lsp_completion_kind| match lsp_completion_kind {
5635 lsp::CompletionItemKind::KEYWORD => Some(0),
5636 lsp::CompletionItemKind::VARIABLE => Some(1),
5637 lsp::CompletionItemKind::CONSTANT => Some(2),
5638 lsp::CompletionItemKind::PROPERTY => Some(3),
5639 _ => None,
5640 })
5641 .unwrap_or(DEFAULT_KIND_KEY);
5642 (kind_key, self.label.filter_text())
5643 }
5644
5645 /// Whether this completion is a snippet.
5646 pub fn is_snippet(&self) -> bool {
5647 self.source
5648 // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5649 .lsp_completion(true)
5650 .is_some_and(|lsp_completion| {
5651 lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5652 })
5653 }
5654
5655 /// Returns the corresponding color for this completion.
5656 ///
5657 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5658 pub fn color(&self) -> Option<Hsla> {
5659 // `lsp::CompletionListItemDefaults` has no `kind` field
5660 let lsp_completion = self.source.lsp_completion(false)?;
5661 if lsp_completion.kind? == CompletionItemKind::COLOR {
5662 return color_extractor::extract_color(&lsp_completion);
5663 }
5664 None
5665 }
5666}
5667
5668fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5669 match level {
5670 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5671 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5672 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5673 }
5674}
5675
5676fn provide_inline_values(
5677 captures: impl Iterator<Item = (Range<usize>, language::DebuggerTextObject)>,
5678 snapshot: &language::BufferSnapshot,
5679 max_row: usize,
5680) -> Vec<InlineValueLocation> {
5681 let mut variables = Vec::new();
5682 let mut variable_position = HashSet::default();
5683 let mut scopes = Vec::new();
5684
5685 let active_debug_line_offset = snapshot.point_to_offset(Point::new(max_row as u32, 0));
5686
5687 for (capture_range, capture_kind) in captures {
5688 match capture_kind {
5689 language::DebuggerTextObject::Variable => {
5690 let variable_name = snapshot
5691 .text_for_range(capture_range.clone())
5692 .collect::<String>();
5693 let point = snapshot.offset_to_point(capture_range.end);
5694
5695 while scopes
5696 .last()
5697 .is_some_and(|scope: &Range<_>| !scope.contains(&capture_range.start))
5698 {
5699 scopes.pop();
5700 }
5701
5702 if point.row as usize > max_row {
5703 break;
5704 }
5705
5706 let scope = if scopes
5707 .last()
5708 .is_none_or(|scope| !scope.contains(&active_debug_line_offset))
5709 {
5710 VariableScope::Global
5711 } else {
5712 VariableScope::Local
5713 };
5714
5715 if variable_position.insert(capture_range.end) {
5716 variables.push(InlineValueLocation {
5717 variable_name,
5718 scope,
5719 lookup: VariableLookupKind::Variable,
5720 row: point.row as usize,
5721 column: point.column as usize,
5722 });
5723 }
5724 }
5725 language::DebuggerTextObject::Scope => {
5726 while scopes.last().map_or_else(
5727 || false,
5728 |scope: &Range<usize>| {
5729 !(scope.contains(&capture_range.start)
5730 && scope.contains(&capture_range.end))
5731 },
5732 ) {
5733 scopes.pop();
5734 }
5735 scopes.push(capture_range);
5736 }
5737 }
5738 }
5739
5740 variables
5741}
5742
5743#[cfg(test)]
5744mod disable_ai_settings_tests {
5745 use super::*;
5746 use gpui::TestAppContext;
5747 use settings::Settings;
5748
5749 #[gpui::test]
5750 async fn test_disable_ai_settings_security(cx: &mut TestAppContext) {
5751 cx.update(|cx| {
5752 settings::init(cx);
5753
5754 // Test 1: Default is false (AI enabled)
5755 assert!(
5756 !DisableAiSettings::get_global(cx).disable_ai,
5757 "Default should allow AI"
5758 );
5759 });
5760
5761 let disable_true = serde_json::json!({
5762 "disable_ai": true
5763 })
5764 .to_string();
5765 let disable_false = serde_json::json!({
5766 "disable_ai": false
5767 })
5768 .to_string();
5769
5770 cx.update_global::<SettingsStore, _>(|store, cx| {
5771 store.set_user_settings(&disable_false, cx).unwrap();
5772 store.set_global_settings(&disable_true, cx).unwrap();
5773 });
5774 cx.update(|cx| {
5775 assert!(
5776 DisableAiSettings::get_global(cx).disable_ai,
5777 "Local false cannot override global true"
5778 );
5779 });
5780
5781 cx.update_global::<SettingsStore, _>(|store, cx| {
5782 store.set_global_settings(&disable_false, cx).unwrap();
5783 store.set_user_settings(&disable_true, cx).unwrap();
5784 });
5785
5786 cx.update(|cx| {
5787 assert!(
5788 DisableAiSettings::get_global(cx).disable_ai,
5789 "Local false cannot override global true"
5790 );
5791 });
5792 }
5793}