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