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