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