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(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
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(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
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(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
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(async move |_, cx| {
1860 let (old_abs_path, new_abs_path) = {
1861 let root_path = worktree.update(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(cx, |worktree, cx| {
1881 worktree.rename_entry(entry_id, new_path.clone(), cx)
1882 })?
1883 .await?;
1884
1885 lsp_store
1886 .update(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(async move |this, cx| {
1938 task.ok_or_else(|| anyhow!("no task"))?.await?;
1939 this.update(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(async move |_project, cx| {
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(async move |this, cx| {
2291 let buffer = buffer.await?;
2292 let handle = this.update(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(async move |project, cx| {
2349 let buffer_id = BufferId::new(request.await?.buffer_id)?;
2350 project
2351 .update(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(async move |this, cx| {
2369 let save_tasks = buffers.into_iter().filter_map(|buffer| {
2370 this.update(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(async move |_, cx| {
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 = ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
2437 image_item.update(cx, |image_item, cx| {
2438 image_item.image_metadata = Some(metadata);
2439 cx.emit(ImageItemEvent::MetadataUpdated);
2440 })?;
2441
2442 Ok(image_item)
2443 })
2444 }
2445
2446 async fn send_buffer_ordered_messages(
2447 this: WeakEntity<Self>,
2448 rx: UnboundedReceiver<BufferOrderedMessage>,
2449 cx: &mut AsyncApp,
2450 ) -> Result<()> {
2451 const MAX_BATCH_SIZE: usize = 128;
2452
2453 let mut operations_by_buffer_id = HashMap::default();
2454 async fn flush_operations(
2455 this: &WeakEntity<Project>,
2456 operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2457 needs_resync_with_host: &mut bool,
2458 is_local: bool,
2459 cx: &mut AsyncApp,
2460 ) -> Result<()> {
2461 for (buffer_id, operations) in operations_by_buffer_id.drain() {
2462 let request = this.update(cx, |this, _| {
2463 let project_id = this.remote_id()?;
2464 Some(this.client.request(proto::UpdateBuffer {
2465 buffer_id: buffer_id.into(),
2466 project_id,
2467 operations,
2468 }))
2469 })?;
2470 if let Some(request) = request {
2471 if request.await.is_err() && !is_local {
2472 *needs_resync_with_host = true;
2473 break;
2474 }
2475 }
2476 }
2477 Ok(())
2478 }
2479
2480 let mut needs_resync_with_host = false;
2481 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2482
2483 while let Some(changes) = changes.next().await {
2484 let is_local = this.update(cx, |this, _| this.is_local())?;
2485
2486 for change in changes {
2487 match change {
2488 BufferOrderedMessage::Operation {
2489 buffer_id,
2490 operation,
2491 } => {
2492 if needs_resync_with_host {
2493 continue;
2494 }
2495
2496 operations_by_buffer_id
2497 .entry(buffer_id)
2498 .or_insert(Vec::new())
2499 .push(operation);
2500 }
2501
2502 BufferOrderedMessage::Resync => {
2503 operations_by_buffer_id.clear();
2504 if this
2505 .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
2506 .await
2507 .is_ok()
2508 {
2509 needs_resync_with_host = false;
2510 }
2511 }
2512
2513 BufferOrderedMessage::LanguageServerUpdate {
2514 language_server_id,
2515 message,
2516 } => {
2517 flush_operations(
2518 &this,
2519 &mut operations_by_buffer_id,
2520 &mut needs_resync_with_host,
2521 is_local,
2522 cx,
2523 )
2524 .await?;
2525
2526 this.update(cx, |this, _| {
2527 if let Some(project_id) = this.remote_id() {
2528 this.client
2529 .send(proto::UpdateLanguageServer {
2530 project_id,
2531 language_server_id: language_server_id.0 as u64,
2532 variant: Some(message),
2533 })
2534 .log_err();
2535 }
2536 })?;
2537 }
2538 }
2539 }
2540
2541 flush_operations(
2542 &this,
2543 &mut operations_by_buffer_id,
2544 &mut needs_resync_with_host,
2545 is_local,
2546 cx,
2547 )
2548 .await?;
2549 }
2550
2551 Ok(())
2552 }
2553
2554 fn on_buffer_store_event(
2555 &mut self,
2556 _: Entity<BufferStore>,
2557 event: &BufferStoreEvent,
2558 cx: &mut Context<Self>,
2559 ) {
2560 match event {
2561 BufferStoreEvent::BufferAdded(buffer) => {
2562 self.register_buffer(buffer, cx).log_err();
2563 }
2564 BufferStoreEvent::BufferDropped(buffer_id) => {
2565 if let Some(ref ssh_client) = self.ssh_client {
2566 ssh_client
2567 .read(cx)
2568 .proto_client()
2569 .send(proto::CloseBuffer {
2570 project_id: 0,
2571 buffer_id: buffer_id.to_proto(),
2572 })
2573 .log_err();
2574 }
2575 }
2576 _ => {}
2577 }
2578 }
2579
2580 fn on_image_store_event(
2581 &mut self,
2582 _: Entity<ImageStore>,
2583 event: &ImageStoreEvent,
2584 cx: &mut Context<Self>,
2585 ) {
2586 match event {
2587 ImageStoreEvent::ImageAdded(image) => {
2588 cx.subscribe(image, |this, image, event, cx| {
2589 this.on_image_event(image, event, cx);
2590 })
2591 .detach();
2592 }
2593 }
2594 }
2595
2596 fn on_dap_store_event(
2597 &mut self,
2598 _: Entity<DapStore>,
2599 event: &DapStoreEvent,
2600 cx: &mut Context<Self>,
2601 ) {
2602 match event {
2603 DapStoreEvent::Notification(message) => {
2604 cx.emit(Event::Toast {
2605 notification_id: "dap".into(),
2606 message: message.clone(),
2607 });
2608 }
2609 _ => {}
2610 }
2611 }
2612
2613 fn on_lsp_store_event(
2614 &mut self,
2615 _: Entity<LspStore>,
2616 event: &LspStoreEvent,
2617 cx: &mut Context<Self>,
2618 ) {
2619 match event {
2620 LspStoreEvent::DiagnosticsUpdated {
2621 language_server_id,
2622 path,
2623 } => cx.emit(Event::DiagnosticsUpdated {
2624 path: path.clone(),
2625 language_server_id: *language_server_id,
2626 }),
2627 LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2628 Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2629 ),
2630 LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2631 cx.emit(Event::LanguageServerRemoved(*language_server_id))
2632 }
2633 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2634 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2635 ),
2636 LspStoreEvent::LanguageDetected {
2637 buffer,
2638 new_language,
2639 } => {
2640 let Some(_) = new_language else {
2641 cx.emit(Event::LanguageNotFound(buffer.clone()));
2642 return;
2643 };
2644 }
2645 LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2646 LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
2647 LspStoreEvent::LanguageServerPrompt(prompt) => {
2648 cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2649 }
2650 LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2651 cx.emit(Event::DiskBasedDiagnosticsStarted {
2652 language_server_id: *language_server_id,
2653 });
2654 }
2655 LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2656 cx.emit(Event::DiskBasedDiagnosticsFinished {
2657 language_server_id: *language_server_id,
2658 });
2659 }
2660 LspStoreEvent::LanguageServerUpdate {
2661 language_server_id,
2662 message,
2663 } => {
2664 if self.is_local() {
2665 self.enqueue_buffer_ordered_message(
2666 BufferOrderedMessage::LanguageServerUpdate {
2667 language_server_id: *language_server_id,
2668 message: message.clone(),
2669 },
2670 )
2671 .ok();
2672 }
2673 }
2674 LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2675 notification_id: "lsp".into(),
2676 message: message.clone(),
2677 }),
2678 LspStoreEvent::SnippetEdit {
2679 buffer_id,
2680 edits,
2681 most_recent_edit,
2682 } => {
2683 if most_recent_edit.replica_id == self.replica_id() {
2684 cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2685 }
2686 }
2687 }
2688 }
2689
2690 fn on_ssh_event(
2691 &mut self,
2692 _: Entity<SshRemoteClient>,
2693 event: &remote::SshRemoteEvent,
2694 cx: &mut Context<Self>,
2695 ) {
2696 match event {
2697 remote::SshRemoteEvent::Disconnected => {
2698 // if self.is_via_ssh() {
2699 // self.collaborators.clear();
2700 self.worktree_store.update(cx, |store, cx| {
2701 store.disconnected_from_host(cx);
2702 });
2703 self.buffer_store.update(cx, |buffer_store, cx| {
2704 buffer_store.disconnected_from_host(cx)
2705 });
2706 self.lsp_store.update(cx, |lsp_store, _cx| {
2707 lsp_store.disconnected_from_ssh_remote()
2708 });
2709 cx.emit(Event::DisconnectedFromSshRemote);
2710 }
2711 }
2712 }
2713
2714 fn on_settings_observer_event(
2715 &mut self,
2716 _: Entity<SettingsObserver>,
2717 event: &SettingsObserverEvent,
2718 cx: &mut Context<Self>,
2719 ) {
2720 match event {
2721 SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2722 Err(InvalidSettingsError::LocalSettings { message, path }) => {
2723 let message =
2724 format!("Failed to set local settings in {:?}:\n{}", path, message);
2725 cx.emit(Event::Toast {
2726 notification_id: "local-settings".into(),
2727 message,
2728 });
2729 }
2730 Ok(_) => cx.emit(Event::HideToast {
2731 notification_id: "local-settings".into(),
2732 }),
2733 Err(_) => {}
2734 },
2735 }
2736 }
2737
2738 fn on_worktree_store_event(
2739 &mut self,
2740 _: Entity<WorktreeStore>,
2741 event: &WorktreeStoreEvent,
2742 cx: &mut Context<Self>,
2743 ) {
2744 match event {
2745 WorktreeStoreEvent::WorktreeAdded(worktree) => {
2746 self.on_worktree_added(worktree, cx);
2747 cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
2748 }
2749 WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2750 cx.emit(Event::WorktreeRemoved(*id));
2751 }
2752 WorktreeStoreEvent::WorktreeReleased(_, id) => {
2753 self.on_worktree_released(*id, cx);
2754 }
2755 WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2756 WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2757 WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
2758 self.client()
2759 .telemetry()
2760 .report_discovered_project_events(*worktree_id, changes);
2761 cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
2762 }
2763 WorktreeStoreEvent::WorktreeUpdatedGitRepositories(worktree_id) => {
2764 cx.emit(Event::WorktreeUpdatedGitRepositories(*worktree_id))
2765 }
2766 WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
2767 cx.emit(Event::DeletedEntry(*worktree_id, *id))
2768 }
2769 }
2770 }
2771
2772 fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
2773 let mut remotely_created_models = self.remotely_created_models.lock();
2774 if remotely_created_models.retain_count > 0 {
2775 remotely_created_models.worktrees.push(worktree.clone())
2776 }
2777 }
2778
2779 fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
2780 if let Some(ssh) = &self.ssh_client {
2781 ssh.read(cx)
2782 .proto_client()
2783 .send(proto::RemoveWorktree {
2784 worktree_id: id_to_remove.to_proto(),
2785 })
2786 .log_err();
2787 }
2788 }
2789
2790 fn on_buffer_event(
2791 &mut self,
2792 buffer: Entity<Buffer>,
2793 event: &BufferEvent,
2794 cx: &mut Context<Self>,
2795 ) -> Option<()> {
2796 if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
2797 self.request_buffer_diff_recalculation(&buffer, cx);
2798 }
2799
2800 let buffer_id = buffer.read(cx).remote_id();
2801 match event {
2802 BufferEvent::ReloadNeeded => {
2803 if !self.is_via_collab() {
2804 self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
2805 .detach_and_log_err(cx);
2806 }
2807 }
2808 BufferEvent::Operation {
2809 operation,
2810 is_local: true,
2811 } => {
2812 let operation = language::proto::serialize_operation(operation);
2813
2814 if let Some(ssh) = &self.ssh_client {
2815 ssh.read(cx)
2816 .proto_client()
2817 .send(proto::UpdateBuffer {
2818 project_id: 0,
2819 buffer_id: buffer_id.to_proto(),
2820 operations: vec![operation.clone()],
2821 })
2822 .ok();
2823 }
2824
2825 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2826 buffer_id,
2827 operation,
2828 })
2829 .ok();
2830 }
2831
2832 _ => {}
2833 }
2834
2835 None
2836 }
2837
2838 fn on_image_event(
2839 &mut self,
2840 image: Entity<ImageItem>,
2841 event: &ImageItemEvent,
2842 cx: &mut Context<Self>,
2843 ) -> Option<()> {
2844 match event {
2845 ImageItemEvent::ReloadNeeded => {
2846 if !self.is_via_collab() {
2847 self.reload_images([image.clone()].into_iter().collect(), cx)
2848 .detach_and_log_err(cx);
2849 }
2850 }
2851 _ => {}
2852 }
2853
2854 None
2855 }
2856
2857 fn request_buffer_diff_recalculation(
2858 &mut self,
2859 buffer: &Entity<Buffer>,
2860 cx: &mut Context<Self>,
2861 ) {
2862 self.buffers_needing_diff.insert(buffer.downgrade());
2863 let first_insertion = self.buffers_needing_diff.len() == 1;
2864
2865 let settings = ProjectSettings::get_global(cx);
2866 let delay = if let Some(delay) = settings.git.gutter_debounce {
2867 delay
2868 } else {
2869 if first_insertion {
2870 let this = cx.weak_entity();
2871 cx.defer(move |cx| {
2872 if let Some(this) = this.upgrade() {
2873 this.update(cx, |this, cx| {
2874 this.recalculate_buffer_diffs(cx).detach();
2875 });
2876 }
2877 });
2878 }
2879 return;
2880 };
2881
2882 const MIN_DELAY: u64 = 50;
2883 let delay = delay.max(MIN_DELAY);
2884 let duration = Duration::from_millis(delay);
2885
2886 self.git_diff_debouncer
2887 .fire_new(duration, cx, move |this, cx| {
2888 this.recalculate_buffer_diffs(cx)
2889 });
2890 }
2891
2892 fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
2893 cx.spawn(async move |this, cx| loop {
2894 let task = this
2895 .update(cx, |this, cx| {
2896 let buffers = this
2897 .buffers_needing_diff
2898 .drain()
2899 .filter_map(|buffer| buffer.upgrade())
2900 .collect::<Vec<_>>();
2901 if buffers.is_empty() {
2902 None
2903 } else {
2904 Some(this.git_store.update(cx, |git_store, cx| {
2905 git_store.recalculate_buffer_diffs(buffers, cx)
2906 }))
2907 }
2908 })
2909 .ok()
2910 .flatten();
2911
2912 if let Some(task) = task {
2913 task.await;
2914 } else {
2915 break;
2916 }
2917 })
2918 }
2919
2920 pub fn set_language_for_buffer(
2921 &mut self,
2922 buffer: &Entity<Buffer>,
2923 new_language: Arc<Language>,
2924 cx: &mut Context<Self>,
2925 ) {
2926 self.lsp_store.update(cx, |lsp_store, cx| {
2927 lsp_store.set_language_for_buffer(buffer, new_language, cx)
2928 })
2929 }
2930
2931 pub fn restart_language_servers_for_buffers(
2932 &mut self,
2933 buffers: Vec<Entity<Buffer>>,
2934 cx: &mut Context<Self>,
2935 ) {
2936 self.lsp_store.update(cx, |lsp_store, cx| {
2937 lsp_store.restart_language_servers_for_buffers(buffers, cx)
2938 })
2939 }
2940
2941 pub fn cancel_language_server_work_for_buffers(
2942 &mut self,
2943 buffers: impl IntoIterator<Item = Entity<Buffer>>,
2944 cx: &mut Context<Self>,
2945 ) {
2946 self.lsp_store.update(cx, |lsp_store, cx| {
2947 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2948 })
2949 }
2950
2951 pub fn cancel_language_server_work(
2952 &mut self,
2953 server_id: LanguageServerId,
2954 token_to_cancel: Option<String>,
2955 cx: &mut Context<Self>,
2956 ) {
2957 self.lsp_store.update(cx, |lsp_store, cx| {
2958 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2959 })
2960 }
2961
2962 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
2963 self.buffer_ordered_messages_tx
2964 .unbounded_send(message)
2965 .map_err(|e| anyhow!(e))
2966 }
2967
2968 pub fn available_toolchains(
2969 &self,
2970 worktree_id: WorktreeId,
2971 language_name: LanguageName,
2972 cx: &App,
2973 ) -> Task<Option<ToolchainList>> {
2974 if let Some(toolchain_store) = self.toolchain_store.clone() {
2975 cx.spawn(async move |cx| {
2976 cx.update(|cx| {
2977 toolchain_store
2978 .read(cx)
2979 .list_toolchains(worktree_id, language_name, cx)
2980 })
2981 .ok()?
2982 .await
2983 })
2984 } else {
2985 Task::ready(None)
2986 }
2987 }
2988
2989 pub async fn toolchain_term(
2990 languages: Arc<LanguageRegistry>,
2991 language_name: LanguageName,
2992 ) -> Option<SharedString> {
2993 languages
2994 .language_for_name(language_name.as_ref())
2995 .await
2996 .ok()?
2997 .toolchain_lister()
2998 .map(|lister| lister.term())
2999 }
3000
3001 pub fn activate_toolchain(
3002 &self,
3003 worktree_id: WorktreeId,
3004 toolchain: Toolchain,
3005 cx: &mut App,
3006 ) -> Task<Option<()>> {
3007 let Some(toolchain_store) = self.toolchain_store.clone() else {
3008 return Task::ready(None);
3009 };
3010 toolchain_store.update(cx, |this, cx| {
3011 this.activate_toolchain(worktree_id, toolchain, cx)
3012 })
3013 }
3014 pub fn active_toolchain(
3015 &self,
3016 worktree_id: WorktreeId,
3017 language_name: LanguageName,
3018 cx: &App,
3019 ) -> Task<Option<Toolchain>> {
3020 let Some(toolchain_store) = self.toolchain_store.clone() else {
3021 return Task::ready(None);
3022 };
3023 toolchain_store
3024 .read(cx)
3025 .active_toolchain(worktree_id, language_name, cx)
3026 }
3027 pub fn language_server_statuses<'a>(
3028 &'a self,
3029 cx: &'a App,
3030 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
3031 self.lsp_store.read(cx).language_server_statuses()
3032 }
3033
3034 pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
3035 self.lsp_store.read(cx).last_formatting_failure()
3036 }
3037
3038 pub fn reset_last_formatting_failure(&self, cx: &mut App) {
3039 self.lsp_store
3040 .update(cx, |store, _| store.reset_last_formatting_failure());
3041 }
3042
3043 pub fn reload_buffers(
3044 &self,
3045 buffers: HashSet<Entity<Buffer>>,
3046 push_to_history: bool,
3047 cx: &mut Context<Self>,
3048 ) -> Task<Result<ProjectTransaction>> {
3049 self.buffer_store.update(cx, |buffer_store, cx| {
3050 buffer_store.reload_buffers(buffers, push_to_history, cx)
3051 })
3052 }
3053
3054 pub fn reload_images(
3055 &self,
3056 images: HashSet<Entity<ImageItem>>,
3057 cx: &mut Context<Self>,
3058 ) -> Task<Result<()>> {
3059 self.image_store
3060 .update(cx, |image_store, cx| image_store.reload_images(images, cx))
3061 }
3062
3063 pub fn format(
3064 &mut self,
3065 buffers: HashSet<Entity<Buffer>>,
3066 target: LspFormatTarget,
3067 push_to_history: bool,
3068 trigger: lsp_store::FormatTrigger,
3069 cx: &mut Context<Project>,
3070 ) -> Task<anyhow::Result<ProjectTransaction>> {
3071 self.lsp_store.update(cx, |lsp_store, cx| {
3072 lsp_store.format(buffers, target, push_to_history, trigger, cx)
3073 })
3074 }
3075
3076 #[inline(never)]
3077 fn definition_impl(
3078 &mut self,
3079 buffer: &Entity<Buffer>,
3080 position: PointUtf16,
3081 cx: &mut Context<Self>,
3082 ) -> Task<Result<Vec<LocationLink>>> {
3083 self.request_lsp(
3084 buffer.clone(),
3085 LanguageServerToQuery::FirstCapable,
3086 GetDefinition { position },
3087 cx,
3088 )
3089 }
3090 pub fn definition<T: ToPointUtf16>(
3091 &mut self,
3092 buffer: &Entity<Buffer>,
3093 position: T,
3094 cx: &mut Context<Self>,
3095 ) -> Task<Result<Vec<LocationLink>>> {
3096 let position = position.to_point_utf16(buffer.read(cx));
3097 self.definition_impl(buffer, position, cx)
3098 }
3099
3100 fn declaration_impl(
3101 &mut self,
3102 buffer: &Entity<Buffer>,
3103 position: PointUtf16,
3104 cx: &mut Context<Self>,
3105 ) -> Task<Result<Vec<LocationLink>>> {
3106 self.request_lsp(
3107 buffer.clone(),
3108 LanguageServerToQuery::FirstCapable,
3109 GetDeclaration { position },
3110 cx,
3111 )
3112 }
3113
3114 pub fn declaration<T: ToPointUtf16>(
3115 &mut self,
3116 buffer: &Entity<Buffer>,
3117 position: T,
3118 cx: &mut Context<Self>,
3119 ) -> Task<Result<Vec<LocationLink>>> {
3120 let position = position.to_point_utf16(buffer.read(cx));
3121 self.declaration_impl(buffer, position, cx)
3122 }
3123
3124 fn type_definition_impl(
3125 &mut self,
3126 buffer: &Entity<Buffer>,
3127 position: PointUtf16,
3128 cx: &mut Context<Self>,
3129 ) -> Task<Result<Vec<LocationLink>>> {
3130 self.request_lsp(
3131 buffer.clone(),
3132 LanguageServerToQuery::FirstCapable,
3133 GetTypeDefinition { position },
3134 cx,
3135 )
3136 }
3137
3138 pub fn type_definition<T: ToPointUtf16>(
3139 &mut self,
3140 buffer: &Entity<Buffer>,
3141 position: T,
3142 cx: &mut Context<Self>,
3143 ) -> Task<Result<Vec<LocationLink>>> {
3144 let position = position.to_point_utf16(buffer.read(cx));
3145 self.type_definition_impl(buffer, position, cx)
3146 }
3147
3148 pub fn implementation<T: ToPointUtf16>(
3149 &mut self,
3150 buffer: &Entity<Buffer>,
3151 position: T,
3152 cx: &mut Context<Self>,
3153 ) -> Task<Result<Vec<LocationLink>>> {
3154 let position = position.to_point_utf16(buffer.read(cx));
3155 self.request_lsp(
3156 buffer.clone(),
3157 LanguageServerToQuery::FirstCapable,
3158 GetImplementation { position },
3159 cx,
3160 )
3161 }
3162
3163 pub fn references<T: ToPointUtf16>(
3164 &mut self,
3165 buffer: &Entity<Buffer>,
3166 position: T,
3167 cx: &mut Context<Self>,
3168 ) -> Task<Result<Vec<Location>>> {
3169 let position = position.to_point_utf16(buffer.read(cx));
3170 self.request_lsp(
3171 buffer.clone(),
3172 LanguageServerToQuery::FirstCapable,
3173 GetReferences { position },
3174 cx,
3175 )
3176 }
3177
3178 fn document_highlights_impl(
3179 &mut self,
3180 buffer: &Entity<Buffer>,
3181 position: PointUtf16,
3182 cx: &mut Context<Self>,
3183 ) -> Task<Result<Vec<DocumentHighlight>>> {
3184 self.request_lsp(
3185 buffer.clone(),
3186 LanguageServerToQuery::FirstCapable,
3187 GetDocumentHighlights { position },
3188 cx,
3189 )
3190 }
3191
3192 pub fn document_highlights<T: ToPointUtf16>(
3193 &mut self,
3194 buffer: &Entity<Buffer>,
3195 position: T,
3196 cx: &mut Context<Self>,
3197 ) -> Task<Result<Vec<DocumentHighlight>>> {
3198 let position = position.to_point_utf16(buffer.read(cx));
3199 self.document_highlights_impl(buffer, position, cx)
3200 }
3201
3202 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
3203 self.lsp_store
3204 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3205 }
3206
3207 pub fn open_buffer_for_symbol(
3208 &mut self,
3209 symbol: &Symbol,
3210 cx: &mut Context<Self>,
3211 ) -> Task<Result<Entity<Buffer>>> {
3212 self.lsp_store.update(cx, |lsp_store, cx| {
3213 lsp_store.open_buffer_for_symbol(symbol, cx)
3214 })
3215 }
3216
3217 pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
3218 let guard = self.retain_remotely_created_models(cx);
3219 let Some(ssh_client) = self.ssh_client.as_ref() else {
3220 return Task::ready(Err(anyhow!("not an ssh project")));
3221 };
3222
3223 let proto_client = ssh_client.read(cx).proto_client();
3224
3225 cx.spawn(async move |project, cx| {
3226 let buffer = proto_client
3227 .request(proto::OpenServerSettings {
3228 project_id: SSH_PROJECT_ID,
3229 })
3230 .await?;
3231
3232 let buffer = project
3233 .update(cx, |project, cx| {
3234 project.buffer_store.update(cx, |buffer_store, cx| {
3235 anyhow::Ok(
3236 buffer_store
3237 .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
3238 )
3239 })
3240 })??
3241 .await;
3242
3243 drop(guard);
3244 buffer
3245 })
3246 }
3247
3248 pub fn open_local_buffer_via_lsp(
3249 &mut self,
3250 abs_path: lsp::Url,
3251 language_server_id: LanguageServerId,
3252 language_server_name: LanguageServerName,
3253 cx: &mut Context<Self>,
3254 ) -> Task<Result<Entity<Buffer>>> {
3255 self.lsp_store.update(cx, |lsp_store, cx| {
3256 lsp_store.open_local_buffer_via_lsp(
3257 abs_path,
3258 language_server_id,
3259 language_server_name,
3260 cx,
3261 )
3262 })
3263 }
3264
3265 pub fn signature_help<T: ToPointUtf16>(
3266 &self,
3267 buffer: &Entity<Buffer>,
3268 position: T,
3269 cx: &mut Context<Self>,
3270 ) -> Task<Vec<SignatureHelp>> {
3271 self.lsp_store.update(cx, |lsp_store, cx| {
3272 lsp_store.signature_help(buffer, position, cx)
3273 })
3274 }
3275
3276 pub fn hover<T: ToPointUtf16>(
3277 &self,
3278 buffer: &Entity<Buffer>,
3279 position: T,
3280 cx: &mut Context<Self>,
3281 ) -> Task<Vec<Hover>> {
3282 let position = position.to_point_utf16(buffer.read(cx));
3283 self.lsp_store
3284 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3285 }
3286
3287 pub fn linked_edit(
3288 &self,
3289 buffer: &Entity<Buffer>,
3290 position: Anchor,
3291 cx: &mut Context<Self>,
3292 ) -> Task<Result<Vec<Range<Anchor>>>> {
3293 self.lsp_store.update(cx, |lsp_store, cx| {
3294 lsp_store.linked_edit(buffer, position, cx)
3295 })
3296 }
3297
3298 pub fn completions<T: ToOffset + ToPointUtf16>(
3299 &self,
3300 buffer: &Entity<Buffer>,
3301 position: T,
3302 context: CompletionContext,
3303 cx: &mut Context<Self>,
3304 ) -> Task<Result<Option<Vec<Completion>>>> {
3305 let position = position.to_point_utf16(buffer.read(cx));
3306 self.lsp_store.update(cx, |lsp_store, cx| {
3307 lsp_store.completions(buffer, position, context, cx)
3308 })
3309 }
3310
3311 pub fn code_actions<T: Clone + ToOffset>(
3312 &mut self,
3313 buffer_handle: &Entity<Buffer>,
3314 range: Range<T>,
3315 kinds: Option<Vec<CodeActionKind>>,
3316 cx: &mut Context<Self>,
3317 ) -> Task<Result<Vec<CodeAction>>> {
3318 let buffer = buffer_handle.read(cx);
3319 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3320 self.lsp_store.update(cx, |lsp_store, cx| {
3321 lsp_store.code_actions(buffer_handle, range, kinds, cx)
3322 })
3323 }
3324
3325 pub fn code_lens<T: Clone + ToOffset>(
3326 &mut self,
3327 buffer_handle: &Entity<Buffer>,
3328 range: Range<T>,
3329 cx: &mut Context<Self>,
3330 ) -> Task<Result<Vec<CodeAction>>> {
3331 let snapshot = buffer_handle.read(cx).snapshot();
3332 let range = snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end);
3333 let code_lens_actions = self
3334 .lsp_store
3335 .update(cx, |lsp_store, cx| lsp_store.code_lens(buffer_handle, cx));
3336
3337 cx.background_spawn(async move {
3338 let mut code_lens_actions = code_lens_actions.await?;
3339 code_lens_actions.retain(|code_lens_action| {
3340 range
3341 .start
3342 .cmp(&code_lens_action.range.start, &snapshot)
3343 .is_ge()
3344 && range
3345 .end
3346 .cmp(&code_lens_action.range.end, &snapshot)
3347 .is_le()
3348 });
3349 Ok(code_lens_actions)
3350 })
3351 }
3352
3353 pub fn apply_code_action(
3354 &self,
3355 buffer_handle: Entity<Buffer>,
3356 action: CodeAction,
3357 push_to_history: bool,
3358 cx: &mut Context<Self>,
3359 ) -> Task<Result<ProjectTransaction>> {
3360 self.lsp_store.update(cx, |lsp_store, cx| {
3361 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3362 })
3363 }
3364
3365 pub fn apply_code_action_kind(
3366 &self,
3367 buffers: HashSet<Entity<Buffer>>,
3368 kind: CodeActionKind,
3369 push_to_history: bool,
3370 cx: &mut Context<Self>,
3371 ) -> Task<Result<ProjectTransaction>> {
3372 self.lsp_store.update(cx, |lsp_store, cx| {
3373 lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
3374 })
3375 }
3376
3377 fn prepare_rename_impl(
3378 &mut self,
3379 buffer: Entity<Buffer>,
3380 position: PointUtf16,
3381 cx: &mut Context<Self>,
3382 ) -> Task<Result<PrepareRenameResponse>> {
3383 self.request_lsp(
3384 buffer,
3385 LanguageServerToQuery::FirstCapable,
3386 PrepareRename { position },
3387 cx,
3388 )
3389 }
3390 pub fn prepare_rename<T: ToPointUtf16>(
3391 &mut self,
3392 buffer: Entity<Buffer>,
3393 position: T,
3394 cx: &mut Context<Self>,
3395 ) -> Task<Result<PrepareRenameResponse>> {
3396 let position = position.to_point_utf16(buffer.read(cx));
3397 self.prepare_rename_impl(buffer, position, cx)
3398 }
3399
3400 pub fn perform_rename<T: ToPointUtf16>(
3401 &mut self,
3402 buffer: Entity<Buffer>,
3403 position: T,
3404 new_name: String,
3405 cx: &mut Context<Self>,
3406 ) -> Task<Result<ProjectTransaction>> {
3407 let push_to_history = true;
3408 let position = position.to_point_utf16(buffer.read(cx));
3409 self.request_lsp(
3410 buffer,
3411 LanguageServerToQuery::FirstCapable,
3412 PerformRename {
3413 position,
3414 new_name,
3415 push_to_history,
3416 },
3417 cx,
3418 )
3419 }
3420
3421 pub fn on_type_format<T: ToPointUtf16>(
3422 &mut self,
3423 buffer: Entity<Buffer>,
3424 position: T,
3425 trigger: String,
3426 push_to_history: bool,
3427 cx: &mut Context<Self>,
3428 ) -> Task<Result<Option<Transaction>>> {
3429 self.lsp_store.update(cx, |lsp_store, cx| {
3430 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3431 })
3432 }
3433
3434 pub fn inlay_hints<T: ToOffset>(
3435 &mut self,
3436 buffer_handle: Entity<Buffer>,
3437 range: Range<T>,
3438 cx: &mut Context<Self>,
3439 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3440 let buffer = buffer_handle.read(cx);
3441 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3442 self.lsp_store.update(cx, |lsp_store, cx| {
3443 lsp_store.inlay_hints(buffer_handle, range, cx)
3444 })
3445 }
3446
3447 pub fn resolve_inlay_hint(
3448 &self,
3449 hint: InlayHint,
3450 buffer_handle: Entity<Buffer>,
3451 server_id: LanguageServerId,
3452 cx: &mut Context<Self>,
3453 ) -> Task<anyhow::Result<InlayHint>> {
3454 self.lsp_store.update(cx, |lsp_store, cx| {
3455 lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3456 })
3457 }
3458
3459 pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
3460 let (result_tx, result_rx) = smol::channel::unbounded();
3461
3462 let matching_buffers_rx = if query.is_opened_only() {
3463 self.sort_search_candidates(&query, cx)
3464 } else {
3465 self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3466 };
3467
3468 cx.spawn(async move |_, cx| {
3469 let mut range_count = 0;
3470 let mut buffer_count = 0;
3471 let mut limit_reached = false;
3472 let query = Arc::new(query);
3473 let mut chunks = matching_buffers_rx.ready_chunks(64);
3474
3475 // Now that we know what paths match the query, we will load at most
3476 // 64 buffers at a time to avoid overwhelming the main thread. For each
3477 // opened buffer, we will spawn a background task that retrieves all the
3478 // ranges in the buffer matched by the query.
3479 let mut chunks = pin!(chunks);
3480 'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3481 let mut chunk_results = Vec::new();
3482 for buffer in matching_buffer_chunk {
3483 let buffer = buffer.clone();
3484 let query = query.clone();
3485 let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot())?;
3486 chunk_results.push(cx.background_spawn(async move {
3487 let ranges = query
3488 .search(&snapshot, None)
3489 .await
3490 .iter()
3491 .map(|range| {
3492 snapshot.anchor_before(range.start)
3493 ..snapshot.anchor_after(range.end)
3494 })
3495 .collect::<Vec<_>>();
3496 anyhow::Ok((buffer, ranges))
3497 }));
3498 }
3499
3500 let chunk_results = futures::future::join_all(chunk_results).await;
3501 for result in chunk_results {
3502 if let Some((buffer, ranges)) = result.log_err() {
3503 range_count += ranges.len();
3504 buffer_count += 1;
3505 result_tx
3506 .send(SearchResult::Buffer { buffer, ranges })
3507 .await?;
3508 if buffer_count > MAX_SEARCH_RESULT_FILES
3509 || range_count > MAX_SEARCH_RESULT_RANGES
3510 {
3511 limit_reached = true;
3512 break 'outer;
3513 }
3514 }
3515 }
3516 }
3517
3518 if limit_reached {
3519 result_tx.send(SearchResult::LimitReached).await?;
3520 }
3521
3522 anyhow::Ok(())
3523 })
3524 .detach();
3525
3526 result_rx
3527 }
3528
3529 fn find_search_candidate_buffers(
3530 &mut self,
3531 query: &SearchQuery,
3532 limit: usize,
3533 cx: &mut Context<Project>,
3534 ) -> Receiver<Entity<Buffer>> {
3535 if self.is_local() {
3536 let fs = self.fs.clone();
3537 self.buffer_store.update(cx, |buffer_store, cx| {
3538 buffer_store.find_search_candidates(query, limit, fs, cx)
3539 })
3540 } else {
3541 self.find_search_candidates_remote(query, limit, cx)
3542 }
3543 }
3544
3545 fn sort_search_candidates(
3546 &mut self,
3547 search_query: &SearchQuery,
3548 cx: &mut Context<Project>,
3549 ) -> Receiver<Entity<Buffer>> {
3550 let worktree_store = self.worktree_store.read(cx);
3551 let mut buffers = search_query
3552 .buffers()
3553 .into_iter()
3554 .flatten()
3555 .filter(|buffer| {
3556 let b = buffer.read(cx);
3557 if let Some(file) = b.file() {
3558 if !search_query.file_matches(file.path()) {
3559 return false;
3560 }
3561 if let Some(entry) = b
3562 .entry_id(cx)
3563 .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3564 {
3565 if entry.is_ignored && !search_query.include_ignored() {
3566 return false;
3567 }
3568 }
3569 }
3570 true
3571 })
3572 .collect::<Vec<_>>();
3573 let (tx, rx) = smol::channel::unbounded();
3574 buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3575 (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3576 (None, Some(_)) => std::cmp::Ordering::Less,
3577 (Some(_), None) => std::cmp::Ordering::Greater,
3578 (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3579 });
3580 for buffer in buffers {
3581 tx.send_blocking(buffer.clone()).unwrap()
3582 }
3583
3584 rx
3585 }
3586
3587 fn find_search_candidates_remote(
3588 &mut self,
3589 query: &SearchQuery,
3590 limit: usize,
3591 cx: &mut Context<Project>,
3592 ) -> Receiver<Entity<Buffer>> {
3593 let (tx, rx) = smol::channel::unbounded();
3594
3595 let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3596 (ssh_client.read(cx).proto_client(), 0)
3597 } else if let Some(remote_id) = self.remote_id() {
3598 (self.client.clone().into(), remote_id)
3599 } else {
3600 return rx;
3601 };
3602
3603 let request = client.request(proto::FindSearchCandidates {
3604 project_id: remote_id,
3605 query: Some(query.to_proto()),
3606 limit: limit as _,
3607 });
3608 let guard = self.retain_remotely_created_models(cx);
3609
3610 cx.spawn(async move |project, cx| {
3611 let response = request.await?;
3612 for buffer_id in response.buffer_ids {
3613 let buffer_id = BufferId::new(buffer_id)?;
3614 let buffer = project
3615 .update(cx, |project, cx| {
3616 project.buffer_store.update(cx, |buffer_store, cx| {
3617 buffer_store.wait_for_remote_buffer(buffer_id, cx)
3618 })
3619 })?
3620 .await?;
3621 let _ = tx.send(buffer).await;
3622 }
3623
3624 drop(guard);
3625 anyhow::Ok(())
3626 })
3627 .detach_and_log_err(cx);
3628 rx
3629 }
3630
3631 pub fn request_lsp<R: LspCommand>(
3632 &mut self,
3633 buffer_handle: Entity<Buffer>,
3634 server: LanguageServerToQuery,
3635 request: R,
3636 cx: &mut Context<Self>,
3637 ) -> Task<Result<R::Response>>
3638 where
3639 <R::LspRequest as lsp::request::Request>::Result: Send,
3640 <R::LspRequest as lsp::request::Request>::Params: Send,
3641 {
3642 let guard = self.retain_remotely_created_models(cx);
3643 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3644 lsp_store.request_lsp(buffer_handle, server, request, cx)
3645 });
3646 cx.spawn(async move |_, _| {
3647 let result = task.await;
3648 drop(guard);
3649 result
3650 })
3651 }
3652
3653 /// Move a worktree to a new position in the worktree order.
3654 ///
3655 /// The worktree will moved to the opposite side of the destination worktree.
3656 ///
3657 /// # Example
3658 ///
3659 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3660 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3661 ///
3662 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3663 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3664 ///
3665 /// # Errors
3666 ///
3667 /// An error will be returned if the worktree or destination worktree are not found.
3668 pub fn move_worktree(
3669 &mut self,
3670 source: WorktreeId,
3671 destination: WorktreeId,
3672 cx: &mut Context<'_, Self>,
3673 ) -> Result<()> {
3674 self.worktree_store.update(cx, |worktree_store, cx| {
3675 worktree_store.move_worktree(source, destination, cx)
3676 })
3677 }
3678
3679 pub fn find_or_create_worktree(
3680 &mut self,
3681 abs_path: impl AsRef<Path>,
3682 visible: bool,
3683 cx: &mut Context<Self>,
3684 ) -> Task<Result<(Entity<Worktree>, PathBuf)>> {
3685 self.worktree_store.update(cx, |worktree_store, cx| {
3686 worktree_store.find_or_create_worktree(abs_path, visible, cx)
3687 })
3688 }
3689
3690 pub fn find_worktree(&self, abs_path: &Path, cx: &App) -> Option<(Entity<Worktree>, PathBuf)> {
3691 self.worktree_store.read_with(cx, |worktree_store, cx| {
3692 worktree_store.find_worktree(abs_path, cx)
3693 })
3694 }
3695
3696 pub fn is_shared(&self) -> bool {
3697 match &self.client_state {
3698 ProjectClientState::Shared { .. } => true,
3699 ProjectClientState::Local => false,
3700 ProjectClientState::Remote { .. } => true,
3701 }
3702 }
3703
3704 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3705 pub fn resolve_path_in_buffer(
3706 &self,
3707 path: &str,
3708 buffer: &Entity<Buffer>,
3709 cx: &mut Context<Self>,
3710 ) -> Task<Option<ResolvedPath>> {
3711 let path_buf = PathBuf::from(path);
3712 if path_buf.is_absolute() || path.starts_with("~") {
3713 self.resolve_abs_path(path, cx)
3714 } else {
3715 self.resolve_path_in_worktrees(path_buf, buffer, cx)
3716 }
3717 }
3718
3719 pub fn resolve_abs_file_path(
3720 &self,
3721 path: &str,
3722 cx: &mut Context<Self>,
3723 ) -> Task<Option<ResolvedPath>> {
3724 let resolve_task = self.resolve_abs_path(path, cx);
3725 cx.background_spawn(async move {
3726 let resolved_path = resolve_task.await;
3727 resolved_path.filter(|path| path.is_file())
3728 })
3729 }
3730
3731 pub fn resolve_abs_path(
3732 &self,
3733 path: &str,
3734 cx: &mut Context<Self>,
3735 ) -> Task<Option<ResolvedPath>> {
3736 if self.is_local() {
3737 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3738 let fs = self.fs.clone();
3739 cx.background_spawn(async move {
3740 let path = expanded.as_path();
3741 let metadata = fs.metadata(path).await.ok().flatten();
3742
3743 metadata.map(|metadata| ResolvedPath::AbsPath {
3744 path: expanded,
3745 is_dir: metadata.is_dir,
3746 })
3747 })
3748 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3749 let request_path = Path::new(path);
3750 let request = ssh_client
3751 .read(cx)
3752 .proto_client()
3753 .request(proto::GetPathMetadata {
3754 project_id: SSH_PROJECT_ID,
3755 path: request_path.to_proto(),
3756 });
3757 cx.background_spawn(async move {
3758 let response = request.await.log_err()?;
3759 if response.exists {
3760 Some(ResolvedPath::AbsPath {
3761 path: PathBuf::from_proto(response.path),
3762 is_dir: response.is_dir,
3763 })
3764 } else {
3765 None
3766 }
3767 })
3768 } else {
3769 return Task::ready(None);
3770 }
3771 }
3772
3773 fn resolve_path_in_worktrees(
3774 &self,
3775 path: PathBuf,
3776 buffer: &Entity<Buffer>,
3777 cx: &mut Context<Self>,
3778 ) -> Task<Option<ResolvedPath>> {
3779 let mut candidates = vec![path.clone()];
3780
3781 if let Some(file) = buffer.read(cx).file() {
3782 if let Some(dir) = file.path().parent() {
3783 let joined = dir.to_path_buf().join(path);
3784 candidates.push(joined);
3785 }
3786 }
3787
3788 let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
3789 let worktrees_with_ids: Vec<_> = self
3790 .worktrees(cx)
3791 .map(|worktree| {
3792 let id = worktree.read(cx).id();
3793 (worktree, id)
3794 })
3795 .collect();
3796
3797 cx.spawn(async move |_, mut cx| {
3798 if let Some(buffer_worktree_id) = buffer_worktree_id {
3799 if let Some((worktree, _)) = worktrees_with_ids
3800 .iter()
3801 .find(|(_, id)| *id == buffer_worktree_id)
3802 {
3803 for candidate in candidates.iter() {
3804 if let Some(path) =
3805 Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3806 {
3807 return Some(path);
3808 }
3809 }
3810 }
3811 }
3812 for (worktree, id) in worktrees_with_ids {
3813 if Some(id) == buffer_worktree_id {
3814 continue;
3815 }
3816 for candidate in candidates.iter() {
3817 if let Some(path) =
3818 Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3819 {
3820 return Some(path);
3821 }
3822 }
3823 }
3824 None
3825 })
3826 }
3827
3828 fn resolve_path_in_worktree(
3829 worktree: &Entity<Worktree>,
3830 path: &PathBuf,
3831 cx: &mut AsyncApp,
3832 ) -> Option<ResolvedPath> {
3833 worktree
3834 .update(cx, |worktree, _| {
3835 let root_entry_path = &worktree.root_entry()?.path;
3836 let resolved = resolve_path(root_entry_path, path);
3837 let stripped = resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3838 worktree.entry_for_path(stripped).map(|entry| {
3839 let project_path = ProjectPath {
3840 worktree_id: worktree.id(),
3841 path: entry.path.clone(),
3842 };
3843 ResolvedPath::ProjectPath {
3844 project_path,
3845 is_dir: entry.is_dir(),
3846 }
3847 })
3848 })
3849 .ok()?
3850 }
3851
3852 pub fn list_directory(
3853 &self,
3854 query: String,
3855 cx: &mut Context<Self>,
3856 ) -> Task<Result<Vec<DirectoryItem>>> {
3857 if self.is_local() {
3858 DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3859 } else if let Some(session) = self.ssh_client.as_ref() {
3860 let path_buf = PathBuf::from(query);
3861 let request = proto::ListRemoteDirectory {
3862 dev_server_id: SSH_PROJECT_ID,
3863 path: path_buf.to_proto(),
3864 config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
3865 };
3866
3867 let response = session.read(cx).proto_client().request(request);
3868 cx.background_spawn(async move {
3869 let proto::ListRemoteDirectoryResponse {
3870 entries,
3871 entry_info,
3872 } = response.await?;
3873 Ok(entries
3874 .into_iter()
3875 .zip(entry_info)
3876 .map(|(entry, info)| DirectoryItem {
3877 path: PathBuf::from(entry),
3878 is_dir: info.is_dir,
3879 })
3880 .collect())
3881 })
3882 } else {
3883 Task::ready(Err(anyhow!("cannot list directory in remote project")))
3884 }
3885 }
3886
3887 pub fn create_worktree(
3888 &mut self,
3889 abs_path: impl AsRef<Path>,
3890 visible: bool,
3891 cx: &mut Context<Self>,
3892 ) -> Task<Result<Entity<Worktree>>> {
3893 self.worktree_store.update(cx, |worktree_store, cx| {
3894 worktree_store.create_worktree(abs_path, visible, cx)
3895 })
3896 }
3897
3898 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3899 self.worktree_store.update(cx, |worktree_store, cx| {
3900 worktree_store.remove_worktree(id_to_remove, cx);
3901 });
3902 }
3903
3904 fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
3905 self.worktree_store.update(cx, |worktree_store, cx| {
3906 worktree_store.add(worktree, cx);
3907 });
3908 }
3909
3910 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
3911 let new_active_entry = entry.and_then(|project_path| {
3912 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3913 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3914 Some(entry.id)
3915 });
3916 if new_active_entry != self.active_entry {
3917 self.active_entry = new_active_entry;
3918 self.lsp_store.update(cx, |lsp_store, _| {
3919 lsp_store.set_active_entry(new_active_entry);
3920 });
3921 cx.emit(Event::ActiveEntryChanged(new_active_entry));
3922 }
3923 }
3924
3925 pub fn language_servers_running_disk_based_diagnostics<'a>(
3926 &'a self,
3927 cx: &'a App,
3928 ) -> impl Iterator<Item = LanguageServerId> + 'a {
3929 self.lsp_store
3930 .read(cx)
3931 .language_servers_running_disk_based_diagnostics()
3932 }
3933
3934 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
3935 self.lsp_store
3936 .read(cx)
3937 .diagnostic_summary(include_ignored, cx)
3938 }
3939
3940 pub fn diagnostic_summaries<'a>(
3941 &'a self,
3942 include_ignored: bool,
3943 cx: &'a App,
3944 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
3945 self.lsp_store
3946 .read(cx)
3947 .diagnostic_summaries(include_ignored, cx)
3948 }
3949
3950 pub fn active_entry(&self) -> Option<ProjectEntryId> {
3951 self.active_entry
3952 }
3953
3954 pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
3955 self.worktree_store.read(cx).entry_for_path(path, cx)
3956 }
3957
3958 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
3959 let worktree = self.worktree_for_entry(entry_id, cx)?;
3960 let worktree = worktree.read(cx);
3961 let worktree_id = worktree.id();
3962 let path = worktree.entry_for_id(entry_id)?.path.clone();
3963 Some(ProjectPath { worktree_id, path })
3964 }
3965
3966 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
3967 self.worktree_for_id(project_path.worktree_id, cx)?
3968 .read(cx)
3969 .absolutize(&project_path.path)
3970 .ok()
3971 }
3972
3973 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
3974 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
3975 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
3976 /// the first visible worktree that has an entry for that relative path.
3977 ///
3978 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
3979 /// root name from paths.
3980 ///
3981 /// # Arguments
3982 ///
3983 /// * `path` - A full path that starts with a worktree root name, or alternatively a
3984 /// relative path within a visible worktree.
3985 /// * `cx` - A reference to the `AppContext`.
3986 ///
3987 /// # Returns
3988 ///
3989 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
3990 pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
3991 let path = path.as_ref();
3992 let worktree_store = self.worktree_store.read(cx);
3993
3994 for worktree in worktree_store.visible_worktrees(cx) {
3995 let worktree_root_name = worktree.read(cx).root_name();
3996 if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
3997 return Some(ProjectPath {
3998 worktree_id: worktree.read(cx).id(),
3999 path: relative_path.into(),
4000 });
4001 }
4002 }
4003
4004 for worktree in worktree_store.visible_worktrees(cx) {
4005 let worktree = worktree.read(cx);
4006 if let Some(entry) = worktree.entry_for_path(path) {
4007 return Some(ProjectPath {
4008 worktree_id: worktree.id(),
4009 path: entry.path.clone(),
4010 });
4011 }
4012 }
4013
4014 None
4015 }
4016
4017 pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4018 self.find_local_worktree(abs_path, cx)
4019 .map(|(worktree, relative_path)| ProjectPath {
4020 worktree_id: worktree.read(cx).id(),
4021 path: relative_path.into(),
4022 })
4023 }
4024
4025 pub fn find_local_worktree(
4026 &self,
4027 abs_path: &Path,
4028 cx: &App,
4029 ) -> Option<(Entity<Worktree>, PathBuf)> {
4030 let trees = self.worktrees(cx);
4031
4032 for tree in trees {
4033 if let Some(relative_path) = abs_path.strip_prefix(tree.read(cx).abs_path()).ok() {
4034 return Some((tree.clone(), relative_path.into()));
4035 }
4036 }
4037 None
4038 }
4039
4040 pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4041 Some(
4042 self.worktree_for_id(project_path.worktree_id, cx)?
4043 .read(cx)
4044 .abs_path()
4045 .to_path_buf(),
4046 )
4047 }
4048
4049 pub fn get_first_worktree_root_repo(&self, cx: &App) -> Option<Arc<dyn GitRepository>> {
4050 let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
4051 let root_entry = worktree.root_git_entry()?;
4052 worktree.get_local_repo(&root_entry)?.repo().clone().into()
4053 }
4054
4055 pub fn blame_buffer(
4056 &self,
4057 buffer: &Entity<Buffer>,
4058 version: Option<clock::Global>,
4059 cx: &App,
4060 ) -> Task<Result<Option<Blame>>> {
4061 self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
4062 }
4063
4064 pub fn get_permalink_to_line(
4065 &self,
4066 buffer: &Entity<Buffer>,
4067 selection: Range<u32>,
4068 cx: &App,
4069 ) -> Task<Result<url::Url>> {
4070 self.buffer_store
4071 .read(cx)
4072 .get_permalink_to_line(buffer, selection, cx)
4073 }
4074
4075 // RPC message handlers
4076
4077 async fn handle_unshare_project(
4078 this: Entity<Self>,
4079 _: TypedEnvelope<proto::UnshareProject>,
4080 mut cx: AsyncApp,
4081 ) -> Result<()> {
4082 this.update(&mut cx, |this, cx| {
4083 if this.is_local() || this.is_via_ssh() {
4084 this.unshare(cx)?;
4085 } else {
4086 this.disconnected_from_host(cx);
4087 }
4088 Ok(())
4089 })?
4090 }
4091
4092 async fn handle_add_collaborator(
4093 this: Entity<Self>,
4094 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4095 mut cx: AsyncApp,
4096 ) -> Result<()> {
4097 let collaborator = envelope
4098 .payload
4099 .collaborator
4100 .take()
4101 .ok_or_else(|| anyhow!("empty collaborator"))?;
4102
4103 let collaborator = Collaborator::from_proto(collaborator)?;
4104 this.update(&mut cx, |this, cx| {
4105 this.buffer_store.update(cx, |buffer_store, _| {
4106 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4107 });
4108 this.breakpoint_store.read(cx).broadcast();
4109 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4110 this.collaborators
4111 .insert(collaborator.peer_id, collaborator);
4112 })?;
4113
4114 Ok(())
4115 }
4116
4117 async fn handle_update_project_collaborator(
4118 this: Entity<Self>,
4119 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4120 mut cx: AsyncApp,
4121 ) -> Result<()> {
4122 let old_peer_id = envelope
4123 .payload
4124 .old_peer_id
4125 .ok_or_else(|| anyhow!("missing old peer id"))?;
4126 let new_peer_id = envelope
4127 .payload
4128 .new_peer_id
4129 .ok_or_else(|| anyhow!("missing new peer id"))?;
4130 this.update(&mut cx, |this, cx| {
4131 let collaborator = this
4132 .collaborators
4133 .remove(&old_peer_id)
4134 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4135 let is_host = collaborator.is_host;
4136 this.collaborators.insert(new_peer_id, collaborator);
4137
4138 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4139 this.buffer_store.update(cx, |buffer_store, _| {
4140 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4141 });
4142
4143 if is_host {
4144 this.buffer_store
4145 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4146 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4147 .unwrap();
4148 cx.emit(Event::HostReshared);
4149 }
4150
4151 cx.emit(Event::CollaboratorUpdated {
4152 old_peer_id,
4153 new_peer_id,
4154 });
4155 Ok(())
4156 })?
4157 }
4158
4159 async fn handle_remove_collaborator(
4160 this: Entity<Self>,
4161 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4162 mut cx: AsyncApp,
4163 ) -> Result<()> {
4164 this.update(&mut cx, |this, cx| {
4165 let peer_id = envelope
4166 .payload
4167 .peer_id
4168 .ok_or_else(|| anyhow!("invalid peer id"))?;
4169 let replica_id = this
4170 .collaborators
4171 .remove(&peer_id)
4172 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4173 .replica_id;
4174 this.buffer_store.update(cx, |buffer_store, cx| {
4175 buffer_store.forget_shared_buffers_for(&peer_id);
4176 for buffer in buffer_store.buffers() {
4177 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4178 }
4179 });
4180 this.git_store.update(cx, |git_store, _| {
4181 git_store.forget_shared_diffs_for(&peer_id);
4182 });
4183
4184 cx.emit(Event::CollaboratorLeft(peer_id));
4185 Ok(())
4186 })?
4187 }
4188
4189 async fn handle_update_project(
4190 this: Entity<Self>,
4191 envelope: TypedEnvelope<proto::UpdateProject>,
4192 mut cx: AsyncApp,
4193 ) -> Result<()> {
4194 this.update(&mut cx, |this, cx| {
4195 // Don't handle messages that were sent before the response to us joining the project
4196 if envelope.message_id > this.join_project_response_message_id {
4197 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4198 }
4199 Ok(())
4200 })?
4201 }
4202
4203 async fn handle_toast(
4204 this: Entity<Self>,
4205 envelope: TypedEnvelope<proto::Toast>,
4206 mut cx: AsyncApp,
4207 ) -> Result<()> {
4208 this.update(&mut cx, |_, cx| {
4209 cx.emit(Event::Toast {
4210 notification_id: envelope.payload.notification_id.into(),
4211 message: envelope.payload.message,
4212 });
4213 Ok(())
4214 })?
4215 }
4216
4217 async fn handle_language_server_prompt_request(
4218 this: Entity<Self>,
4219 envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4220 mut cx: AsyncApp,
4221 ) -> Result<proto::LanguageServerPromptResponse> {
4222 let (tx, mut rx) = smol::channel::bounded(1);
4223 let actions: Vec<_> = envelope
4224 .payload
4225 .actions
4226 .into_iter()
4227 .map(|action| MessageActionItem {
4228 title: action,
4229 properties: Default::default(),
4230 })
4231 .collect();
4232 this.update(&mut cx, |_, cx| {
4233 cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4234 level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4235 message: envelope.payload.message,
4236 actions: actions.clone(),
4237 lsp_name: envelope.payload.lsp_name,
4238 response_channel: tx,
4239 }));
4240
4241 anyhow::Ok(())
4242 })??;
4243
4244 // We drop `this` to avoid holding a reference in this future for too
4245 // long.
4246 // If we keep the reference, we might not drop the `Project` early
4247 // enough when closing a window and it will only get releases on the
4248 // next `flush_effects()` call.
4249 drop(this);
4250
4251 let mut rx = pin!(rx);
4252 let answer = rx.next().await;
4253
4254 Ok(LanguageServerPromptResponse {
4255 action_response: answer.and_then(|answer| {
4256 actions
4257 .iter()
4258 .position(|action| *action == answer)
4259 .map(|index| index as u64)
4260 }),
4261 })
4262 }
4263
4264 async fn handle_hide_toast(
4265 this: Entity<Self>,
4266 envelope: TypedEnvelope<proto::HideToast>,
4267 mut cx: AsyncApp,
4268 ) -> Result<()> {
4269 this.update(&mut cx, |_, cx| {
4270 cx.emit(Event::HideToast {
4271 notification_id: envelope.payload.notification_id.into(),
4272 });
4273 Ok(())
4274 })?
4275 }
4276
4277 // Collab sends UpdateWorktree protos as messages
4278 async fn handle_update_worktree(
4279 this: Entity<Self>,
4280 envelope: TypedEnvelope<proto::UpdateWorktree>,
4281 mut cx: AsyncApp,
4282 ) -> Result<()> {
4283 this.update(&mut cx, |this, cx| {
4284 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4285 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4286 worktree.update(cx, |worktree, _| {
4287 let worktree = worktree.as_remote_mut().unwrap();
4288 worktree.update_from_remote(envelope.payload);
4289 });
4290 }
4291 Ok(())
4292 })?
4293 }
4294
4295 async fn handle_update_buffer_from_ssh(
4296 this: Entity<Self>,
4297 envelope: TypedEnvelope<proto::UpdateBuffer>,
4298 cx: AsyncApp,
4299 ) -> Result<proto::Ack> {
4300 let buffer_store = this.read_with(&cx, |this, cx| {
4301 if let Some(remote_id) = this.remote_id() {
4302 let mut payload = envelope.payload.clone();
4303 payload.project_id = remote_id;
4304 cx.background_spawn(this.client.request(payload))
4305 .detach_and_log_err(cx);
4306 }
4307 this.buffer_store.clone()
4308 })?;
4309 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4310 }
4311
4312 async fn handle_update_buffer(
4313 this: Entity<Self>,
4314 envelope: TypedEnvelope<proto::UpdateBuffer>,
4315 cx: AsyncApp,
4316 ) -> Result<proto::Ack> {
4317 let buffer_store = this.read_with(&cx, |this, cx| {
4318 if let Some(ssh) = &this.ssh_client {
4319 let mut payload = envelope.payload.clone();
4320 payload.project_id = SSH_PROJECT_ID;
4321 cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4322 .detach_and_log_err(cx);
4323 }
4324 this.buffer_store.clone()
4325 })?;
4326 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4327 }
4328
4329 fn retain_remotely_created_models(
4330 &mut self,
4331 cx: &mut Context<Self>,
4332 ) -> RemotelyCreatedModelGuard {
4333 {
4334 let mut remotely_create_models = self.remotely_created_models.lock();
4335 if remotely_create_models.retain_count == 0 {
4336 remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
4337 remotely_create_models.worktrees =
4338 self.worktree_store.read(cx).worktrees().collect();
4339 }
4340 remotely_create_models.retain_count += 1;
4341 }
4342 RemotelyCreatedModelGuard {
4343 remote_models: Arc::downgrade(&self.remotely_created_models),
4344 }
4345 }
4346
4347 async fn handle_create_buffer_for_peer(
4348 this: Entity<Self>,
4349 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4350 mut cx: AsyncApp,
4351 ) -> Result<()> {
4352 this.update(&mut cx, |this, cx| {
4353 this.buffer_store.update(cx, |buffer_store, cx| {
4354 buffer_store.handle_create_buffer_for_peer(
4355 envelope,
4356 this.replica_id(),
4357 this.capability(),
4358 cx,
4359 )
4360 })
4361 })?
4362 }
4363
4364 async fn handle_synchronize_buffers(
4365 this: Entity<Self>,
4366 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4367 mut cx: AsyncApp,
4368 ) -> Result<proto::SynchronizeBuffersResponse> {
4369 let response = this.update(&mut cx, |this, cx| {
4370 let client = this.client.clone();
4371 this.buffer_store.update(cx, |this, cx| {
4372 this.handle_synchronize_buffers(envelope, cx, client)
4373 })
4374 })??;
4375
4376 Ok(response)
4377 }
4378
4379 async fn handle_search_candidate_buffers(
4380 this: Entity<Self>,
4381 envelope: TypedEnvelope<proto::FindSearchCandidates>,
4382 mut cx: AsyncApp,
4383 ) -> Result<proto::FindSearchCandidatesResponse> {
4384 let peer_id = envelope.original_sender_id()?;
4385 let message = envelope.payload;
4386 let query = SearchQuery::from_proto(
4387 message
4388 .query
4389 .ok_or_else(|| anyhow!("missing query field"))?,
4390 )?;
4391 let results = this.update(&mut cx, |this, cx| {
4392 this.find_search_candidate_buffers(&query, message.limit as _, cx)
4393 })?;
4394
4395 let mut response = proto::FindSearchCandidatesResponse {
4396 buffer_ids: Vec::new(),
4397 };
4398
4399 while let Ok(buffer) = results.recv().await {
4400 this.update(&mut cx, |this, cx| {
4401 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4402 response.buffer_ids.push(buffer_id.to_proto());
4403 })?;
4404 }
4405
4406 Ok(response)
4407 }
4408
4409 async fn handle_open_buffer_by_id(
4410 this: Entity<Self>,
4411 envelope: TypedEnvelope<proto::OpenBufferById>,
4412 mut cx: AsyncApp,
4413 ) -> Result<proto::OpenBufferResponse> {
4414 let peer_id = envelope.original_sender_id()?;
4415 let buffer_id = BufferId::new(envelope.payload.id)?;
4416 let buffer = this
4417 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4418 .await?;
4419 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4420 }
4421
4422 async fn handle_open_buffer_by_path(
4423 this: Entity<Self>,
4424 envelope: TypedEnvelope<proto::OpenBufferByPath>,
4425 mut cx: AsyncApp,
4426 ) -> Result<proto::OpenBufferResponse> {
4427 let peer_id = envelope.original_sender_id()?;
4428 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4429 let open_buffer = this.update(&mut cx, |this, cx| {
4430 this.open_buffer(
4431 ProjectPath {
4432 worktree_id,
4433 path: Arc::<Path>::from_proto(envelope.payload.path),
4434 },
4435 cx,
4436 )
4437 })?;
4438
4439 let buffer = open_buffer.await?;
4440 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4441 }
4442
4443 async fn handle_open_new_buffer(
4444 this: Entity<Self>,
4445 envelope: TypedEnvelope<proto::OpenNewBuffer>,
4446 mut cx: AsyncApp,
4447 ) -> Result<proto::OpenBufferResponse> {
4448 let buffer = this
4449 .update(&mut cx, |this, cx| this.create_buffer(cx))?
4450 .await?;
4451 let peer_id = envelope.original_sender_id()?;
4452
4453 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4454 }
4455
4456 fn respond_to_open_buffer_request(
4457 this: Entity<Self>,
4458 buffer: Entity<Buffer>,
4459 peer_id: proto::PeerId,
4460 cx: &mut AsyncApp,
4461 ) -> Result<proto::OpenBufferResponse> {
4462 this.update(cx, |this, cx| {
4463 let is_private = buffer
4464 .read(cx)
4465 .file()
4466 .map(|f| f.is_private())
4467 .unwrap_or_default();
4468 if is_private {
4469 Err(anyhow!(ErrorCode::UnsharedItem))
4470 } else {
4471 Ok(proto::OpenBufferResponse {
4472 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4473 })
4474 }
4475 })?
4476 }
4477
4478 fn create_buffer_for_peer(
4479 &mut self,
4480 buffer: &Entity<Buffer>,
4481 peer_id: proto::PeerId,
4482 cx: &mut App,
4483 ) -> BufferId {
4484 self.buffer_store
4485 .update(cx, |buffer_store, cx| {
4486 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4487 })
4488 .detach_and_log_err(cx);
4489 buffer.read(cx).remote_id()
4490 }
4491
4492 fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4493 let project_id = match self.client_state {
4494 ProjectClientState::Remote {
4495 sharing_has_stopped,
4496 remote_id,
4497 ..
4498 } => {
4499 if sharing_has_stopped {
4500 return Task::ready(Err(anyhow!(
4501 "can't synchronize remote buffers on a readonly project"
4502 )));
4503 } else {
4504 remote_id
4505 }
4506 }
4507 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4508 return Task::ready(Err(anyhow!(
4509 "can't synchronize remote buffers on a local project"
4510 )))
4511 }
4512 };
4513
4514 let client = self.client.clone();
4515 cx.spawn(async move |this, cx| {
4516 let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
4517 this.buffer_store.read(cx).buffer_version_info(cx)
4518 })?;
4519 let response = client
4520 .request(proto::SynchronizeBuffers {
4521 project_id,
4522 buffers,
4523 })
4524 .await?;
4525
4526 let send_updates_for_buffers = this.update(cx, |this, cx| {
4527 response
4528 .buffers
4529 .into_iter()
4530 .map(|buffer| {
4531 let client = client.clone();
4532 let buffer_id = match BufferId::new(buffer.id) {
4533 Ok(id) => id,
4534 Err(e) => {
4535 return Task::ready(Err(e));
4536 }
4537 };
4538 let remote_version = language::proto::deserialize_version(&buffer.version);
4539 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4540 let operations =
4541 buffer.read(cx).serialize_ops(Some(remote_version), cx);
4542 cx.background_spawn(async move {
4543 let operations = operations.await;
4544 for chunk in split_operations(operations) {
4545 client
4546 .request(proto::UpdateBuffer {
4547 project_id,
4548 buffer_id: buffer_id.into(),
4549 operations: chunk,
4550 })
4551 .await?;
4552 }
4553 anyhow::Ok(())
4554 })
4555 } else {
4556 Task::ready(Ok(()))
4557 }
4558 })
4559 .collect::<Vec<_>>()
4560 })?;
4561
4562 // Any incomplete buffers have open requests waiting. Request that the host sends
4563 // creates these buffers for us again to unblock any waiting futures.
4564 for id in incomplete_buffer_ids {
4565 cx.background_spawn(client.request(proto::OpenBufferById {
4566 project_id,
4567 id: id.into(),
4568 }))
4569 .detach();
4570 }
4571
4572 futures::future::join_all(send_updates_for_buffers)
4573 .await
4574 .into_iter()
4575 .collect()
4576 })
4577 }
4578
4579 pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4580 self.worktree_store.read(cx).worktree_metadata_protos(cx)
4581 }
4582
4583 /// Iterator of all open buffers that have unsaved changes
4584 pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4585 self.buffer_store.read(cx).buffers().filter_map(|buf| {
4586 let buf = buf.read(cx);
4587 if buf.is_dirty() {
4588 buf.project_path(cx)
4589 } else {
4590 None
4591 }
4592 })
4593 }
4594
4595 fn set_worktrees_from_proto(
4596 &mut self,
4597 worktrees: Vec<proto::WorktreeMetadata>,
4598 cx: &mut Context<Project>,
4599 ) -> Result<()> {
4600 self.worktree_store.update(cx, |worktree_store, cx| {
4601 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4602 })
4603 }
4604
4605 fn set_collaborators_from_proto(
4606 &mut self,
4607 messages: Vec<proto::Collaborator>,
4608 cx: &mut Context<Self>,
4609 ) -> Result<()> {
4610 let mut collaborators = HashMap::default();
4611 for message in messages {
4612 let collaborator = Collaborator::from_proto(message)?;
4613 collaborators.insert(collaborator.peer_id, collaborator);
4614 }
4615 for old_peer_id in self.collaborators.keys() {
4616 if !collaborators.contains_key(old_peer_id) {
4617 cx.emit(Event::CollaboratorLeft(*old_peer_id));
4618 }
4619 }
4620 self.collaborators = collaborators;
4621 Ok(())
4622 }
4623
4624 pub fn supplementary_language_servers<'a>(
4625 &'a self,
4626 cx: &'a App,
4627 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4628 self.lsp_store.read(cx).supplementary_language_servers()
4629 }
4630
4631 pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
4632 self.lsp_store.update(cx, |this, cx| {
4633 this.language_servers_for_local_buffer(buffer, cx)
4634 .any(
4635 |(_, server)| match server.capabilities().inlay_hint_provider {
4636 Some(lsp::OneOf::Left(enabled)) => enabled,
4637 Some(lsp::OneOf::Right(_)) => true,
4638 None => false,
4639 },
4640 )
4641 })
4642 }
4643
4644 pub fn language_server_id_for_name(
4645 &self,
4646 buffer: &Buffer,
4647 name: &str,
4648 cx: &mut App,
4649 ) -> Option<LanguageServerId> {
4650 self.lsp_store.update(cx, |this, cx| {
4651 this.language_servers_for_local_buffer(buffer, cx)
4652 .find_map(|(adapter, server)| {
4653 if adapter.name.0 == name {
4654 Some(server.server_id())
4655 } else {
4656 None
4657 }
4658 })
4659 })
4660 }
4661
4662 pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
4663 self.lsp_store.update(cx, |this, cx| {
4664 this.language_servers_for_local_buffer(buffer, cx)
4665 .next()
4666 .is_some()
4667 })
4668 }
4669
4670 pub fn git_init(
4671 &self,
4672 path: Arc<Path>,
4673 fallback_branch_name: String,
4674 cx: &App,
4675 ) -> Task<Result<()>> {
4676 self.git_store
4677 .read(cx)
4678 .git_init(path, fallback_branch_name, cx)
4679 }
4680
4681 pub fn buffer_store(&self) -> &Entity<BufferStore> {
4682 &self.buffer_store
4683 }
4684
4685 pub fn git_store(&self) -> &Entity<GitStore> {
4686 &self.git_store
4687 }
4688
4689 pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
4690 self.git_store.read(cx).active_repository()
4691 }
4692
4693 pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<ProjectEntryId, Entity<Repository>> {
4694 self.git_store.read(cx).repositories()
4695 }
4696
4697 pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
4698 self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
4699 }
4700}
4701
4702fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
4703 code_actions
4704 .iter()
4705 .flat_map(|(kind, enabled)| {
4706 if *enabled {
4707 Some(kind.clone().into())
4708 } else {
4709 None
4710 }
4711 })
4712 .collect()
4713}
4714
4715pub struct PathMatchCandidateSet {
4716 pub snapshot: Snapshot,
4717 pub include_ignored: bool,
4718 pub include_root_name: bool,
4719 pub candidates: Candidates,
4720}
4721
4722pub enum Candidates {
4723 /// Only consider directories.
4724 Directories,
4725 /// Only consider files.
4726 Files,
4727 /// Consider directories and files.
4728 Entries,
4729}
4730
4731impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4732 type Candidates = PathMatchCandidateSetIter<'a>;
4733
4734 fn id(&self) -> usize {
4735 self.snapshot.id().to_usize()
4736 }
4737
4738 fn len(&self) -> usize {
4739 match self.candidates {
4740 Candidates::Files => {
4741 if self.include_ignored {
4742 self.snapshot.file_count()
4743 } else {
4744 self.snapshot.visible_file_count()
4745 }
4746 }
4747
4748 Candidates::Directories => {
4749 if self.include_ignored {
4750 self.snapshot.dir_count()
4751 } else {
4752 self.snapshot.visible_dir_count()
4753 }
4754 }
4755
4756 Candidates::Entries => {
4757 if self.include_ignored {
4758 self.snapshot.entry_count()
4759 } else {
4760 self.snapshot.visible_entry_count()
4761 }
4762 }
4763 }
4764 }
4765
4766 fn prefix(&self) -> Arc<str> {
4767 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
4768 self.snapshot.root_name().into()
4769 } else if self.include_root_name {
4770 format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
4771 } else {
4772 Arc::default()
4773 }
4774 }
4775
4776 fn candidates(&'a self, start: usize) -> Self::Candidates {
4777 PathMatchCandidateSetIter {
4778 traversal: match self.candidates {
4779 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
4780 Candidates::Files => self.snapshot.files(self.include_ignored, start),
4781 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
4782 },
4783 }
4784 }
4785}
4786
4787pub struct PathMatchCandidateSetIter<'a> {
4788 traversal: Traversal<'a>,
4789}
4790
4791impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
4792 type Item = fuzzy::PathMatchCandidate<'a>;
4793
4794 fn next(&mut self) -> Option<Self::Item> {
4795 self.traversal
4796 .next()
4797 .map(|entry| fuzzy::PathMatchCandidate {
4798 is_dir: entry.kind.is_dir(),
4799 path: &entry.path,
4800 char_bag: entry.char_bag,
4801 })
4802 }
4803}
4804
4805impl EventEmitter<Event> for Project {}
4806
4807impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
4808 fn from(val: &'a ProjectPath) -> Self {
4809 SettingsLocation {
4810 worktree_id: val.worktree_id,
4811 path: val.path.as_ref(),
4812 }
4813 }
4814}
4815
4816impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
4817 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
4818 Self {
4819 worktree_id,
4820 path: path.as_ref().into(),
4821 }
4822 }
4823}
4824
4825pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
4826 let mut path_components = path.components();
4827 let mut base_components = base.components();
4828 let mut components: Vec<Component> = Vec::new();
4829 loop {
4830 match (path_components.next(), base_components.next()) {
4831 (None, None) => break,
4832 (Some(a), None) => {
4833 components.push(a);
4834 components.extend(path_components.by_ref());
4835 break;
4836 }
4837 (None, _) => components.push(Component::ParentDir),
4838 (Some(a), Some(b)) if components.is_empty() && a == b => (),
4839 (Some(a), Some(Component::CurDir)) => components.push(a),
4840 (Some(a), Some(_)) => {
4841 components.push(Component::ParentDir);
4842 for _ in base_components {
4843 components.push(Component::ParentDir);
4844 }
4845 components.push(a);
4846 components.extend(path_components.by_ref());
4847 break;
4848 }
4849 }
4850 }
4851 components.iter().map(|c| c.as_os_str()).collect()
4852}
4853
4854fn resolve_path(base: &Path, path: &Path) -> PathBuf {
4855 let mut result = base.to_path_buf();
4856 for component in path.components() {
4857 match component {
4858 Component::ParentDir => {
4859 result.pop();
4860 }
4861 Component::CurDir => (),
4862 _ => result.push(component),
4863 }
4864 }
4865 result
4866}
4867
4868/// ResolvedPath is a path that has been resolved to either a ProjectPath
4869/// or an AbsPath and that *exists*.
4870#[derive(Debug, Clone)]
4871pub enum ResolvedPath {
4872 ProjectPath {
4873 project_path: ProjectPath,
4874 is_dir: bool,
4875 },
4876 AbsPath {
4877 path: PathBuf,
4878 is_dir: bool,
4879 },
4880}
4881
4882impl ResolvedPath {
4883 pub fn abs_path(&self) -> Option<&Path> {
4884 match self {
4885 Self::AbsPath { path, .. } => Some(path.as_path()),
4886 _ => None,
4887 }
4888 }
4889
4890 pub fn project_path(&self) -> Option<&ProjectPath> {
4891 match self {
4892 Self::ProjectPath { project_path, .. } => Some(&project_path),
4893 _ => None,
4894 }
4895 }
4896
4897 pub fn is_file(&self) -> bool {
4898 !self.is_dir()
4899 }
4900
4901 pub fn is_dir(&self) -> bool {
4902 match self {
4903 Self::ProjectPath { is_dir, .. } => *is_dir,
4904 Self::AbsPath { is_dir, .. } => *is_dir,
4905 }
4906 }
4907}
4908
4909impl ProjectItem for Buffer {
4910 fn try_open(
4911 project: &Entity<Project>,
4912 path: &ProjectPath,
4913 cx: &mut App,
4914 ) -> Option<Task<Result<Entity<Self>>>> {
4915 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
4916 }
4917
4918 fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
4919 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
4920 }
4921
4922 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
4923 File::from_dyn(self.file()).map(|file| ProjectPath {
4924 worktree_id: file.worktree_id(cx),
4925 path: file.path().clone(),
4926 })
4927 }
4928
4929 fn is_dirty(&self) -> bool {
4930 self.is_dirty()
4931 }
4932}
4933
4934impl Completion {
4935 /// A key that can be used to sort completions when displaying
4936 /// them to the user.
4937 pub fn sort_key(&self) -> (usize, &str) {
4938 const DEFAULT_KIND_KEY: usize = 2;
4939 let kind_key = self
4940 .source
4941 // `lsp::CompletionListItemDefaults` has no `kind` field
4942 .lsp_completion(false)
4943 .and_then(|lsp_completion| lsp_completion.kind)
4944 .and_then(|lsp_completion_kind| match lsp_completion_kind {
4945 lsp::CompletionItemKind::KEYWORD => Some(0),
4946 lsp::CompletionItemKind::VARIABLE => Some(1),
4947 _ => None,
4948 })
4949 .unwrap_or(DEFAULT_KIND_KEY);
4950 (kind_key, &self.label.text[self.label.filter_range.clone()])
4951 }
4952
4953 /// Whether this completion is a snippet.
4954 pub fn is_snippet(&self) -> bool {
4955 self.source
4956 // `lsp::CompletionListItemDefaults` has `insert_text_format` field
4957 .lsp_completion(true)
4958 .map_or(false, |lsp_completion| {
4959 lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
4960 })
4961 }
4962
4963 /// Returns the corresponding color for this completion.
4964 ///
4965 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
4966 pub fn color(&self) -> Option<Hsla> {
4967 // `lsp::CompletionListItemDefaults` has no `kind` field
4968 let lsp_completion = self.source.lsp_completion(false)?;
4969 if lsp_completion.kind? == CompletionItemKind::COLOR {
4970 return color_extractor::extract_color(&lsp_completion);
4971 }
4972 None
4973 }
4974}
4975
4976pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
4977 entries.sort_by(|entry_a, entry_b| {
4978 let entry_a = entry_a.as_ref();
4979 let entry_b = entry_b.as_ref();
4980 compare_paths(
4981 (&entry_a.path, entry_a.is_file()),
4982 (&entry_b.path, entry_b.is_file()),
4983 )
4984 });
4985}
4986
4987fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
4988 match level {
4989 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
4990 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
4991 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
4992 }
4993}