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::Operation {
2316 operation,
2317 is_local: true,
2318 } => {
2319 let operation = language::proto::serialize_operation(operation);
2320
2321 if let Some(ssh) = &self.ssh_client {
2322 ssh.read(cx)
2323 .proto_client()
2324 .send(proto::UpdateBuffer {
2325 project_id: 0,
2326 buffer_id: buffer_id.to_proto(),
2327 operations: vec![operation.clone()],
2328 })
2329 .ok();
2330 }
2331
2332 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2333 buffer_id,
2334 operation,
2335 })
2336 .ok();
2337 }
2338
2339 _ => {}
2340 }
2341
2342 None
2343 }
2344
2345 fn request_buffer_diff_recalculation(
2346 &mut self,
2347 buffer: &Model<Buffer>,
2348 cx: &mut ModelContext<Self>,
2349 ) {
2350 self.buffers_needing_diff.insert(buffer.downgrade());
2351 let first_insertion = self.buffers_needing_diff.len() == 1;
2352
2353 let settings = ProjectSettings::get_global(cx);
2354 let delay = if let Some(delay) = settings.git.gutter_debounce {
2355 delay
2356 } else {
2357 if first_insertion {
2358 let this = cx.weak_model();
2359 cx.defer(move |cx| {
2360 if let Some(this) = this.upgrade() {
2361 this.update(cx, |this, cx| {
2362 this.recalculate_buffer_diffs(cx).detach();
2363 });
2364 }
2365 });
2366 }
2367 return;
2368 };
2369
2370 const MIN_DELAY: u64 = 50;
2371 let delay = delay.max(MIN_DELAY);
2372 let duration = Duration::from_millis(delay);
2373
2374 self.git_diff_debouncer
2375 .fire_new(duration, cx, move |this, cx| {
2376 this.recalculate_buffer_diffs(cx)
2377 });
2378 }
2379
2380 fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2381 let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
2382 cx.spawn(move |this, mut cx| async move {
2383 let tasks: Vec<_> = buffers
2384 .iter()
2385 .filter_map(|buffer| {
2386 let buffer = buffer.upgrade()?;
2387 buffer
2388 .update(&mut cx, |buffer, cx| buffer.recalculate_diff(cx))
2389 .ok()
2390 .flatten()
2391 })
2392 .collect();
2393
2394 futures::future::join_all(tasks).await;
2395
2396 this.update(&mut cx, |this, cx| {
2397 if this.buffers_needing_diff.is_empty() {
2398 // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2399 for buffer in buffers {
2400 if let Some(buffer) = buffer.upgrade() {
2401 buffer.update(cx, |_, cx| cx.notify());
2402 }
2403 }
2404 } else {
2405 this.recalculate_buffer_diffs(cx).detach();
2406 }
2407 })
2408 .ok();
2409 })
2410 }
2411
2412 pub fn set_language_for_buffer(
2413 &mut self,
2414 buffer: &Model<Buffer>,
2415 new_language: Arc<Language>,
2416 cx: &mut ModelContext<Self>,
2417 ) {
2418 self.lsp_store.update(cx, |lsp_store, cx| {
2419 lsp_store.set_language_for_buffer(buffer, new_language, cx)
2420 })
2421 }
2422
2423 pub fn restart_language_servers_for_buffers(
2424 &mut self,
2425 buffers: impl IntoIterator<Item = Model<Buffer>>,
2426 cx: &mut ModelContext<Self>,
2427 ) {
2428 self.lsp_store.update(cx, |lsp_store, cx| {
2429 lsp_store.restart_language_servers_for_buffers(buffers, cx)
2430 })
2431 }
2432
2433 pub fn cancel_language_server_work_for_buffers(
2434 &mut self,
2435 buffers: impl IntoIterator<Item = Model<Buffer>>,
2436 cx: &mut ModelContext<Self>,
2437 ) {
2438 self.lsp_store.update(cx, |lsp_store, cx| {
2439 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2440 })
2441 }
2442
2443 pub fn cancel_language_server_work(
2444 &mut self,
2445 server_id: LanguageServerId,
2446 token_to_cancel: Option<String>,
2447 cx: &mut ModelContext<Self>,
2448 ) {
2449 self.lsp_store.update(cx, |lsp_store, cx| {
2450 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2451 })
2452 }
2453
2454 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
2455 self.buffer_ordered_messages_tx
2456 .unbounded_send(message)
2457 .map_err(|e| anyhow!(e))
2458 }
2459
2460 pub fn language_server_statuses<'a>(
2461 &'a self,
2462 cx: &'a AppContext,
2463 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
2464 self.lsp_store.read(cx).language_server_statuses()
2465 }
2466
2467 pub fn last_formatting_failure<'a>(&self, cx: &'a AppContext) -> Option<&'a str> {
2468 self.lsp_store.read(cx).last_formatting_failure()
2469 }
2470
2471 pub fn update_diagnostics(
2472 &mut self,
2473 language_server_id: LanguageServerId,
2474 params: lsp::PublishDiagnosticsParams,
2475 disk_based_sources: &[String],
2476 cx: &mut ModelContext<Self>,
2477 ) -> Result<()> {
2478 self.lsp_store.update(cx, |lsp_store, cx| {
2479 lsp_store.update_diagnostics(language_server_id, params, disk_based_sources, cx)
2480 })
2481 }
2482
2483 pub fn update_diagnostic_entries(
2484 &mut self,
2485 server_id: LanguageServerId,
2486 abs_path: PathBuf,
2487 version: Option<i32>,
2488 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2489 cx: &mut ModelContext<Project>,
2490 ) -> Result<(), anyhow::Error> {
2491 self.lsp_store.update(cx, |lsp_store, cx| {
2492 lsp_store.update_diagnostic_entries(server_id, abs_path, version, diagnostics, cx)
2493 })
2494 }
2495
2496 pub fn reload_buffers(
2497 &self,
2498 buffers: HashSet<Model<Buffer>>,
2499 push_to_history: bool,
2500 cx: &mut ModelContext<Self>,
2501 ) -> Task<Result<ProjectTransaction>> {
2502 self.buffer_store.update(cx, |buffer_store, cx| {
2503 buffer_store.reload_buffers(buffers, push_to_history, cx)
2504 })
2505 }
2506
2507 pub fn format(
2508 &mut self,
2509 buffers: HashSet<Model<Buffer>>,
2510 push_to_history: bool,
2511 trigger: lsp_store::FormatTrigger,
2512 target: lsp_store::FormatTarget,
2513 cx: &mut ModelContext<Project>,
2514 ) -> Task<anyhow::Result<ProjectTransaction>> {
2515 self.lsp_store.update(cx, |lsp_store, cx| {
2516 lsp_store.format(buffers, push_to_history, trigger, target, cx)
2517 })
2518 }
2519
2520 #[inline(never)]
2521 fn definition_impl(
2522 &mut self,
2523 buffer: &Model<Buffer>,
2524 position: PointUtf16,
2525 cx: &mut ModelContext<Self>,
2526 ) -> Task<Result<Vec<LocationLink>>> {
2527 self.request_lsp(
2528 buffer.clone(),
2529 LanguageServerToQuery::Primary,
2530 GetDefinition { position },
2531 cx,
2532 )
2533 }
2534 pub fn definition<T: ToPointUtf16>(
2535 &mut self,
2536 buffer: &Model<Buffer>,
2537 position: T,
2538 cx: &mut ModelContext<Self>,
2539 ) -> Task<Result<Vec<LocationLink>>> {
2540 let position = position.to_point_utf16(buffer.read(cx));
2541 self.definition_impl(buffer, position, cx)
2542 }
2543
2544 fn declaration_impl(
2545 &mut self,
2546 buffer: &Model<Buffer>,
2547 position: PointUtf16,
2548 cx: &mut ModelContext<Self>,
2549 ) -> Task<Result<Vec<LocationLink>>> {
2550 self.request_lsp(
2551 buffer.clone(),
2552 LanguageServerToQuery::Primary,
2553 GetDeclaration { position },
2554 cx,
2555 )
2556 }
2557
2558 pub fn declaration<T: ToPointUtf16>(
2559 &mut self,
2560 buffer: &Model<Buffer>,
2561 position: T,
2562 cx: &mut ModelContext<Self>,
2563 ) -> Task<Result<Vec<LocationLink>>> {
2564 let position = position.to_point_utf16(buffer.read(cx));
2565 self.declaration_impl(buffer, position, cx)
2566 }
2567
2568 fn type_definition_impl(
2569 &mut self,
2570 buffer: &Model<Buffer>,
2571 position: PointUtf16,
2572 cx: &mut ModelContext<Self>,
2573 ) -> Task<Result<Vec<LocationLink>>> {
2574 self.request_lsp(
2575 buffer.clone(),
2576 LanguageServerToQuery::Primary,
2577 GetTypeDefinition { position },
2578 cx,
2579 )
2580 }
2581
2582 pub fn type_definition<T: ToPointUtf16>(
2583 &mut self,
2584 buffer: &Model<Buffer>,
2585 position: T,
2586 cx: &mut ModelContext<Self>,
2587 ) -> Task<Result<Vec<LocationLink>>> {
2588 let position = position.to_point_utf16(buffer.read(cx));
2589 self.type_definition_impl(buffer, position, cx)
2590 }
2591
2592 pub fn implementation<T: ToPointUtf16>(
2593 &mut self,
2594 buffer: &Model<Buffer>,
2595 position: T,
2596 cx: &mut ModelContext<Self>,
2597 ) -> Task<Result<Vec<LocationLink>>> {
2598 let position = position.to_point_utf16(buffer.read(cx));
2599 self.request_lsp(
2600 buffer.clone(),
2601 LanguageServerToQuery::Primary,
2602 GetImplementation { position },
2603 cx,
2604 )
2605 }
2606
2607 pub fn references<T: ToPointUtf16>(
2608 &mut self,
2609 buffer: &Model<Buffer>,
2610 position: T,
2611 cx: &mut ModelContext<Self>,
2612 ) -> Task<Result<Vec<Location>>> {
2613 let position = position.to_point_utf16(buffer.read(cx));
2614 self.request_lsp(
2615 buffer.clone(),
2616 LanguageServerToQuery::Primary,
2617 GetReferences { position },
2618 cx,
2619 )
2620 }
2621
2622 fn document_highlights_impl(
2623 &mut self,
2624 buffer: &Model<Buffer>,
2625 position: PointUtf16,
2626 cx: &mut ModelContext<Self>,
2627 ) -> Task<Result<Vec<DocumentHighlight>>> {
2628 self.request_lsp(
2629 buffer.clone(),
2630 LanguageServerToQuery::Primary,
2631 GetDocumentHighlights { position },
2632 cx,
2633 )
2634 }
2635
2636 pub fn document_highlights<T: ToPointUtf16>(
2637 &mut self,
2638 buffer: &Model<Buffer>,
2639 position: T,
2640 cx: &mut ModelContext<Self>,
2641 ) -> Task<Result<Vec<DocumentHighlight>>> {
2642 let position = position.to_point_utf16(buffer.read(cx));
2643 self.document_highlights_impl(buffer, position, cx)
2644 }
2645
2646 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
2647 self.lsp_store
2648 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
2649 }
2650
2651 pub fn open_buffer_for_symbol(
2652 &mut self,
2653 symbol: &Symbol,
2654 cx: &mut ModelContext<Self>,
2655 ) -> Task<Result<Model<Buffer>>> {
2656 self.lsp_store.update(cx, |lsp_store, cx| {
2657 lsp_store.open_buffer_for_symbol(symbol, cx)
2658 })
2659 }
2660
2661 pub fn open_server_settings(
2662 &mut self,
2663 cx: &mut ModelContext<Self>,
2664 ) -> Task<Result<Model<Buffer>>> {
2665 let guard = self.retain_remotely_created_models(cx);
2666 let Some(ssh_client) = self.ssh_client.as_ref() else {
2667 return Task::ready(Err(anyhow!("not an ssh project")));
2668 };
2669
2670 let proto_client = ssh_client.read(cx).proto_client();
2671
2672 cx.spawn(|this, mut cx| async move {
2673 let buffer = proto_client
2674 .request(proto::OpenServerSettings {
2675 project_id: SSH_PROJECT_ID,
2676 })
2677 .await?;
2678
2679 let buffer = this
2680 .update(&mut cx, |this, cx| {
2681 anyhow::Ok(this.wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx))
2682 })??
2683 .await;
2684
2685 drop(guard);
2686 buffer
2687 })
2688 }
2689
2690 pub fn open_local_buffer_via_lsp(
2691 &mut self,
2692 abs_path: lsp::Url,
2693 language_server_id: LanguageServerId,
2694 language_server_name: LanguageServerName,
2695 cx: &mut ModelContext<Self>,
2696 ) -> Task<Result<Model<Buffer>>> {
2697 self.lsp_store.update(cx, |lsp_store, cx| {
2698 lsp_store.open_local_buffer_via_lsp(
2699 abs_path,
2700 language_server_id,
2701 language_server_name,
2702 cx,
2703 )
2704 })
2705 }
2706
2707 pub fn signature_help<T: ToPointUtf16>(
2708 &self,
2709 buffer: &Model<Buffer>,
2710 position: T,
2711 cx: &mut ModelContext<Self>,
2712 ) -> Task<Vec<SignatureHelp>> {
2713 self.lsp_store.update(cx, |lsp_store, cx| {
2714 lsp_store.signature_help(buffer, position, cx)
2715 })
2716 }
2717
2718 pub fn hover<T: ToPointUtf16>(
2719 &self,
2720 buffer: &Model<Buffer>,
2721 position: T,
2722 cx: &mut ModelContext<Self>,
2723 ) -> Task<Vec<Hover>> {
2724 let position = position.to_point_utf16(buffer.read(cx));
2725 self.lsp_store
2726 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
2727 }
2728
2729 pub fn linked_edit(
2730 &self,
2731 buffer: &Model<Buffer>,
2732 position: Anchor,
2733 cx: &mut ModelContext<Self>,
2734 ) -> Task<Result<Vec<Range<Anchor>>>> {
2735 self.lsp_store.update(cx, |lsp_store, cx| {
2736 lsp_store.linked_edit(buffer, position, cx)
2737 })
2738 }
2739
2740 pub fn completions<T: ToOffset + ToPointUtf16>(
2741 &self,
2742 buffer: &Model<Buffer>,
2743 position: T,
2744 context: CompletionContext,
2745 cx: &mut ModelContext<Self>,
2746 ) -> Task<Result<Vec<Completion>>> {
2747 let position = position.to_point_utf16(buffer.read(cx));
2748 self.lsp_store.update(cx, |lsp_store, cx| {
2749 lsp_store.completions(buffer, position, context, cx)
2750 })
2751 }
2752
2753 pub fn resolve_completions(
2754 &self,
2755 buffer: Model<Buffer>,
2756 completion_indices: Vec<usize>,
2757 completions: Arc<RwLock<Box<[Completion]>>>,
2758 cx: &mut ModelContext<Self>,
2759 ) -> Task<Result<bool>> {
2760 self.lsp_store.update(cx, |lsp_store, cx| {
2761 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
2762 })
2763 }
2764
2765 pub fn apply_additional_edits_for_completion(
2766 &self,
2767 buffer_handle: Model<Buffer>,
2768 completion: Completion,
2769 push_to_history: bool,
2770 cx: &mut ModelContext<Self>,
2771 ) -> Task<Result<Option<Transaction>>> {
2772 self.lsp_store.update(cx, |lsp_store, cx| {
2773 lsp_store.apply_additional_edits_for_completion(
2774 buffer_handle,
2775 completion,
2776 push_to_history,
2777 cx,
2778 )
2779 })
2780 }
2781
2782 pub fn code_actions<T: Clone + ToOffset>(
2783 &mut self,
2784 buffer_handle: &Model<Buffer>,
2785 range: Range<T>,
2786 cx: &mut ModelContext<Self>,
2787 ) -> Task<Result<Vec<CodeAction>>> {
2788 let buffer = buffer_handle.read(cx);
2789 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2790 self.lsp_store.update(cx, |lsp_store, cx| {
2791 lsp_store.code_actions(buffer_handle, range, cx)
2792 })
2793 }
2794
2795 pub fn apply_code_action(
2796 &self,
2797 buffer_handle: Model<Buffer>,
2798 action: CodeAction,
2799 push_to_history: bool,
2800 cx: &mut ModelContext<Self>,
2801 ) -> Task<Result<ProjectTransaction>> {
2802 self.lsp_store.update(cx, |lsp_store, cx| {
2803 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
2804 })
2805 }
2806
2807 fn prepare_rename_impl(
2808 &mut self,
2809 buffer: Model<Buffer>,
2810 position: PointUtf16,
2811 cx: &mut ModelContext<Self>,
2812 ) -> Task<Result<Option<Range<Anchor>>>> {
2813 self.request_lsp(
2814 buffer,
2815 LanguageServerToQuery::Primary,
2816 PrepareRename { position },
2817 cx,
2818 )
2819 }
2820 pub fn prepare_rename<T: ToPointUtf16>(
2821 &mut self,
2822 buffer: Model<Buffer>,
2823 position: T,
2824 cx: &mut ModelContext<Self>,
2825 ) -> Task<Result<Option<Range<Anchor>>>> {
2826 let position = position.to_point_utf16(buffer.read(cx));
2827 self.prepare_rename_impl(buffer, position, cx)
2828 }
2829
2830 fn perform_rename_impl(
2831 &mut self,
2832 buffer: Model<Buffer>,
2833 position: PointUtf16,
2834 new_name: String,
2835 push_to_history: bool,
2836 cx: &mut ModelContext<Self>,
2837 ) -> Task<Result<ProjectTransaction>> {
2838 let position = position.to_point_utf16(buffer.read(cx));
2839 self.request_lsp(
2840 buffer,
2841 LanguageServerToQuery::Primary,
2842 PerformRename {
2843 position,
2844 new_name,
2845 push_to_history,
2846 },
2847 cx,
2848 )
2849 }
2850
2851 pub fn perform_rename<T: ToPointUtf16>(
2852 &mut self,
2853 buffer: Model<Buffer>,
2854 position: T,
2855 new_name: String,
2856 cx: &mut ModelContext<Self>,
2857 ) -> Task<Result<ProjectTransaction>> {
2858 let position = position.to_point_utf16(buffer.read(cx));
2859 self.perform_rename_impl(buffer, position, new_name, true, cx)
2860 }
2861
2862 pub fn on_type_format<T: ToPointUtf16>(
2863 &mut self,
2864 buffer: Model<Buffer>,
2865 position: T,
2866 trigger: String,
2867 push_to_history: bool,
2868 cx: &mut ModelContext<Self>,
2869 ) -> Task<Result<Option<Transaction>>> {
2870 self.lsp_store.update(cx, |lsp_store, cx| {
2871 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
2872 })
2873 }
2874
2875 pub fn inlay_hints<T: ToOffset>(
2876 &mut self,
2877 buffer_handle: Model<Buffer>,
2878 range: Range<T>,
2879 cx: &mut ModelContext<Self>,
2880 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
2881 let buffer = buffer_handle.read(cx);
2882 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2883 self.lsp_store.update(cx, |lsp_store, cx| {
2884 lsp_store.inlay_hints(buffer_handle, range, cx)
2885 })
2886 }
2887
2888 pub fn resolve_inlay_hint(
2889 &self,
2890 hint: InlayHint,
2891 buffer_handle: Model<Buffer>,
2892 server_id: LanguageServerId,
2893 cx: &mut ModelContext<Self>,
2894 ) -> Task<anyhow::Result<InlayHint>> {
2895 self.lsp_store.update(cx, |lsp_store, cx| {
2896 lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
2897 })
2898 }
2899
2900 pub fn search(
2901 &mut self,
2902 query: SearchQuery,
2903 cx: &mut ModelContext<Self>,
2904 ) -> Receiver<SearchResult> {
2905 let (result_tx, result_rx) = smol::channel::unbounded();
2906
2907 let matching_buffers_rx = if query.is_opened_only() {
2908 self.sort_search_candidates(&query, cx)
2909 } else {
2910 self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
2911 };
2912
2913 cx.spawn(|_, cx| async move {
2914 let mut range_count = 0;
2915 let mut buffer_count = 0;
2916 let mut limit_reached = false;
2917 let query = Arc::new(query);
2918 let mut chunks = matching_buffers_rx.ready_chunks(64);
2919
2920 // Now that we know what paths match the query, we will load at most
2921 // 64 buffers at a time to avoid overwhelming the main thread. For each
2922 // opened buffer, we will spawn a background task that retrieves all the
2923 // ranges in the buffer matched by the query.
2924 'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
2925 let mut chunk_results = Vec::new();
2926 for buffer in matching_buffer_chunk {
2927 let buffer = buffer.clone();
2928 let query = query.clone();
2929 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
2930 chunk_results.push(cx.background_executor().spawn(async move {
2931 let ranges = query
2932 .search(&snapshot, None)
2933 .await
2934 .iter()
2935 .map(|range| {
2936 snapshot.anchor_before(range.start)
2937 ..snapshot.anchor_after(range.end)
2938 })
2939 .collect::<Vec<_>>();
2940 anyhow::Ok((buffer, ranges))
2941 }));
2942 }
2943
2944 let chunk_results = futures::future::join_all(chunk_results).await;
2945 for result in chunk_results {
2946 if let Some((buffer, ranges)) = result.log_err() {
2947 range_count += ranges.len();
2948 buffer_count += 1;
2949 result_tx
2950 .send(SearchResult::Buffer { buffer, ranges })
2951 .await?;
2952 if buffer_count > MAX_SEARCH_RESULT_FILES
2953 || range_count > MAX_SEARCH_RESULT_RANGES
2954 {
2955 limit_reached = true;
2956 break 'outer;
2957 }
2958 }
2959 }
2960 }
2961
2962 if limit_reached {
2963 result_tx.send(SearchResult::LimitReached).await?;
2964 }
2965
2966 anyhow::Ok(())
2967 })
2968 .detach();
2969
2970 result_rx
2971 }
2972
2973 fn find_search_candidate_buffers(
2974 &mut self,
2975 query: &SearchQuery,
2976 limit: usize,
2977 cx: &mut ModelContext<Project>,
2978 ) -> Receiver<Model<Buffer>> {
2979 if self.is_local() {
2980 let fs = self.fs.clone();
2981 self.buffer_store.update(cx, |buffer_store, cx| {
2982 buffer_store.find_search_candidates(query, limit, fs, cx)
2983 })
2984 } else {
2985 self.find_search_candidates_remote(query, limit, cx)
2986 }
2987 }
2988
2989 fn sort_search_candidates(
2990 &mut self,
2991 search_query: &SearchQuery,
2992 cx: &mut ModelContext<Project>,
2993 ) -> Receiver<Model<Buffer>> {
2994 let worktree_store = self.worktree_store.read(cx);
2995 let mut buffers = search_query
2996 .buffers()
2997 .into_iter()
2998 .flatten()
2999 .filter(|buffer| {
3000 let b = buffer.read(cx);
3001 if let Some(file) = b.file() {
3002 if !search_query.file_matches(file.path()) {
3003 return false;
3004 }
3005 if let Some(entry) = b
3006 .entry_id(cx)
3007 .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3008 {
3009 if entry.is_ignored && !search_query.include_ignored() {
3010 return false;
3011 }
3012 }
3013 }
3014 true
3015 })
3016 .collect::<Vec<_>>();
3017 let (tx, rx) = smol::channel::unbounded();
3018 buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3019 (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3020 (None, Some(_)) => std::cmp::Ordering::Less,
3021 (Some(_), None) => std::cmp::Ordering::Greater,
3022 (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3023 });
3024 for buffer in buffers {
3025 tx.send_blocking(buffer.clone()).unwrap()
3026 }
3027
3028 rx
3029 }
3030
3031 fn find_search_candidates_remote(
3032 &mut self,
3033 query: &SearchQuery,
3034 limit: usize,
3035 cx: &mut ModelContext<Project>,
3036 ) -> Receiver<Model<Buffer>> {
3037 let (tx, rx) = smol::channel::unbounded();
3038
3039 let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3040 (ssh_client.read(cx).proto_client(), 0)
3041 } else if let Some(remote_id) = self.remote_id() {
3042 (self.client.clone().into(), remote_id)
3043 } else {
3044 return rx;
3045 };
3046
3047 let request = client.request(proto::FindSearchCandidates {
3048 project_id: remote_id,
3049 query: Some(query.to_proto()),
3050 limit: limit as _,
3051 });
3052 let guard = self.retain_remotely_created_models(cx);
3053
3054 cx.spawn(move |this, mut cx| async move {
3055 let response = request.await?;
3056 for buffer_id in response.buffer_ids {
3057 let buffer_id = BufferId::new(buffer_id)?;
3058 let buffer = this
3059 .update(&mut cx, |this, cx| {
3060 this.wait_for_remote_buffer(buffer_id, cx)
3061 })?
3062 .await?;
3063 let _ = tx.send(buffer).await;
3064 }
3065
3066 drop(guard);
3067 anyhow::Ok(())
3068 })
3069 .detach_and_log_err(cx);
3070 rx
3071 }
3072
3073 pub fn request_lsp<R: LspCommand>(
3074 &mut self,
3075 buffer_handle: Model<Buffer>,
3076 server: LanguageServerToQuery,
3077 request: R,
3078 cx: &mut ModelContext<Self>,
3079 ) -> Task<Result<R::Response>>
3080 where
3081 <R::LspRequest as lsp::request::Request>::Result: Send,
3082 <R::LspRequest as lsp::request::Request>::Params: Send,
3083 {
3084 let guard = self.retain_remotely_created_models(cx);
3085 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3086 lsp_store.request_lsp(buffer_handle, server, request, cx)
3087 });
3088 cx.spawn(|_, _| async move {
3089 let result = task.await;
3090 drop(guard);
3091 result
3092 })
3093 }
3094
3095 /// Move a worktree to a new position in the worktree order.
3096 ///
3097 /// The worktree will moved to the opposite side of the destination worktree.
3098 ///
3099 /// # Example
3100 ///
3101 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3102 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3103 ///
3104 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3105 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3106 ///
3107 /// # Errors
3108 ///
3109 /// An error will be returned if the worktree or destination worktree are not found.
3110 pub fn move_worktree(
3111 &mut self,
3112 source: WorktreeId,
3113 destination: WorktreeId,
3114 cx: &mut ModelContext<'_, Self>,
3115 ) -> Result<()> {
3116 self.worktree_store.update(cx, |worktree_store, cx| {
3117 worktree_store.move_worktree(source, destination, cx)
3118 })
3119 }
3120
3121 pub fn find_or_create_worktree(
3122 &mut self,
3123 abs_path: impl AsRef<Path>,
3124 visible: bool,
3125 cx: &mut ModelContext<Self>,
3126 ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
3127 self.worktree_store.update(cx, |worktree_store, cx| {
3128 worktree_store.find_or_create_worktree(abs_path, visible, cx)
3129 })
3130 }
3131
3132 pub fn find_worktree(
3133 &self,
3134 abs_path: &Path,
3135 cx: &AppContext,
3136 ) -> Option<(Model<Worktree>, PathBuf)> {
3137 self.worktree_store.read_with(cx, |worktree_store, cx| {
3138 worktree_store.find_worktree(abs_path, cx)
3139 })
3140 }
3141
3142 pub fn is_shared(&self) -> bool {
3143 match &self.client_state {
3144 ProjectClientState::Shared { .. } => true,
3145 ProjectClientState::Local => false,
3146 ProjectClientState::Remote { in_room, .. } => *in_room,
3147 }
3148 }
3149
3150 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3151 pub fn resolve_existing_file_path(
3152 &self,
3153 path: &str,
3154 buffer: &Model<Buffer>,
3155 cx: &mut ModelContext<Self>,
3156 ) -> Task<Option<ResolvedPath>> {
3157 let path_buf = PathBuf::from(path);
3158 if path_buf.is_absolute() || path.starts_with("~") {
3159 self.resolve_abs_file_path(path, cx)
3160 } else {
3161 self.resolve_path_in_worktrees(path_buf, buffer, cx)
3162 }
3163 }
3164
3165 pub fn abs_file_path_exists(&self, path: &str, cx: &mut ModelContext<Self>) -> Task<bool> {
3166 let resolve_task = self.resolve_abs_file_path(path, cx);
3167 cx.background_executor().spawn(async move {
3168 let resolved_path = resolve_task.await;
3169 resolved_path.is_some()
3170 })
3171 }
3172
3173 fn resolve_abs_file_path(
3174 &self,
3175 path: &str,
3176 cx: &mut ModelContext<Self>,
3177 ) -> Task<Option<ResolvedPath>> {
3178 if self.is_local() {
3179 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3180
3181 let fs = self.fs.clone();
3182 cx.background_executor().spawn(async move {
3183 let path = expanded.as_path();
3184 let exists = fs.is_file(path).await;
3185
3186 exists.then(|| ResolvedPath::AbsPath(expanded))
3187 })
3188 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3189 let request = ssh_client
3190 .read(cx)
3191 .proto_client()
3192 .request(proto::CheckFileExists {
3193 project_id: SSH_PROJECT_ID,
3194 path: path.to_string(),
3195 });
3196 cx.background_executor().spawn(async move {
3197 let response = request.await.log_err()?;
3198 if response.exists {
3199 Some(ResolvedPath::AbsPath(PathBuf::from(response.path)))
3200 } else {
3201 None
3202 }
3203 })
3204 } else {
3205 return Task::ready(None);
3206 }
3207 }
3208
3209 fn resolve_path_in_worktrees(
3210 &self,
3211 path: PathBuf,
3212 buffer: &Model<Buffer>,
3213 cx: &mut ModelContext<Self>,
3214 ) -> Task<Option<ResolvedPath>> {
3215 let mut candidates = vec![path.clone()];
3216
3217 if let Some(file) = buffer.read(cx).file() {
3218 if let Some(dir) = file.path().parent() {
3219 let joined = dir.to_path_buf().join(path);
3220 candidates.push(joined);
3221 }
3222 }
3223
3224 let worktrees = self.worktrees(cx).collect::<Vec<_>>();
3225 cx.spawn(|_, mut cx| async move {
3226 for worktree in worktrees {
3227 for candidate in candidates.iter() {
3228 let path = worktree
3229 .update(&mut cx, |worktree, _| {
3230 let root_entry_path = &worktree.root_entry()?.path;
3231
3232 let resolved = resolve_path(root_entry_path, candidate);
3233
3234 let stripped =
3235 resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3236
3237 worktree.entry_for_path(stripped).map(|entry| {
3238 ResolvedPath::ProjectPath(ProjectPath {
3239 worktree_id: worktree.id(),
3240 path: entry.path.clone(),
3241 })
3242 })
3243 })
3244 .ok()?;
3245
3246 if path.is_some() {
3247 return path;
3248 }
3249 }
3250 }
3251 None
3252 })
3253 }
3254
3255 pub fn list_directory(
3256 &self,
3257 query: String,
3258 cx: &mut ModelContext<Self>,
3259 ) -> Task<Result<Vec<PathBuf>>> {
3260 if self.is_local() {
3261 DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3262 } else if let Some(session) = self.ssh_client.as_ref() {
3263 let request = proto::ListRemoteDirectory {
3264 dev_server_id: SSH_PROJECT_ID,
3265 path: query,
3266 };
3267
3268 let response = session.read(cx).proto_client().request(request);
3269 cx.background_executor().spawn(async move {
3270 let response = response.await?;
3271 Ok(response.entries.into_iter().map(PathBuf::from).collect())
3272 })
3273 } else if let Some(dev_server) = self.dev_server_project_id().and_then(|id| {
3274 dev_server_projects::Store::global(cx)
3275 .read(cx)
3276 .dev_server_for_project(id)
3277 }) {
3278 let request = proto::ListRemoteDirectory {
3279 dev_server_id: dev_server.id.0,
3280 path: query,
3281 };
3282 let response = self.client.request(request);
3283 cx.background_executor().spawn(async move {
3284 let response = response.await?;
3285 Ok(response.entries.into_iter().map(PathBuf::from).collect())
3286 })
3287 } else {
3288 Task::ready(Err(anyhow!("cannot list directory in remote project")))
3289 }
3290 }
3291
3292 pub fn create_worktree(
3293 &mut self,
3294 abs_path: impl AsRef<Path>,
3295 visible: bool,
3296 cx: &mut ModelContext<Self>,
3297 ) -> Task<Result<Model<Worktree>>> {
3298 self.worktree_store.update(cx, |worktree_store, cx| {
3299 worktree_store.create_worktree(abs_path, visible, cx)
3300 })
3301 }
3302
3303 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
3304 self.worktree_store.update(cx, |worktree_store, cx| {
3305 worktree_store.remove_worktree(id_to_remove, cx);
3306 });
3307 }
3308
3309 fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
3310 self.worktree_store.update(cx, |worktree_store, cx| {
3311 worktree_store.add(worktree, cx);
3312 });
3313 }
3314
3315 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
3316 let new_active_entry = entry.and_then(|project_path| {
3317 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3318 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3319 Some(entry.id)
3320 });
3321 if new_active_entry != self.active_entry {
3322 self.active_entry = new_active_entry;
3323 self.lsp_store.update(cx, |lsp_store, _| {
3324 lsp_store.set_active_entry(new_active_entry);
3325 });
3326 cx.emit(Event::ActiveEntryChanged(new_active_entry));
3327 }
3328 }
3329
3330 pub fn language_servers_running_disk_based_diagnostics<'a>(
3331 &'a self,
3332 cx: &'a AppContext,
3333 ) -> impl Iterator<Item = LanguageServerId> + 'a {
3334 self.lsp_store
3335 .read(cx)
3336 .language_servers_running_disk_based_diagnostics()
3337 }
3338
3339 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
3340 let mut summary = DiagnosticSummary::default();
3341 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
3342 summary.error_count += path_summary.error_count;
3343 summary.warning_count += path_summary.warning_count;
3344 }
3345 summary
3346 }
3347
3348 pub fn diagnostic_summaries<'a>(
3349 &'a self,
3350 include_ignored: bool,
3351 cx: &'a AppContext,
3352 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
3353 self.lsp_store
3354 .read(cx)
3355 .diagnostic_summaries(include_ignored, cx)
3356 }
3357
3358 pub fn active_entry(&self) -> Option<ProjectEntryId> {
3359 self.active_entry
3360 }
3361
3362 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
3363 self.worktree_store.read(cx).entry_for_path(path, cx)
3364 }
3365
3366 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
3367 let worktree = self.worktree_for_entry(entry_id, cx)?;
3368 let worktree = worktree.read(cx);
3369 let worktree_id = worktree.id();
3370 let path = worktree.entry_for_id(entry_id)?.path.clone();
3371 Some(ProjectPath { worktree_id, path })
3372 }
3373
3374 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
3375 let workspace_root = self
3376 .worktree_for_id(project_path.worktree_id, cx)?
3377 .read(cx)
3378 .abs_path();
3379 let project_path = project_path.path.as_ref();
3380
3381 Some(if project_path == Path::new("") {
3382 workspace_root.to_path_buf()
3383 } else {
3384 workspace_root.join(project_path)
3385 })
3386 }
3387
3388 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
3389 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
3390 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
3391 /// the first visible worktree that has an entry for that relative path.
3392 ///
3393 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
3394 /// root name from paths.
3395 ///
3396 /// # Arguments
3397 ///
3398 /// * `path` - A full path that starts with a worktree root name, or alternatively a
3399 /// relative path within a visible worktree.
3400 /// * `cx` - A reference to the `AppContext`.
3401 ///
3402 /// # Returns
3403 ///
3404 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
3405 pub fn find_project_path(&self, path: &Path, cx: &AppContext) -> Option<ProjectPath> {
3406 let worktree_store = self.worktree_store.read(cx);
3407
3408 for worktree in worktree_store.visible_worktrees(cx) {
3409 let worktree_root_name = worktree.read(cx).root_name();
3410 if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
3411 return Some(ProjectPath {
3412 worktree_id: worktree.read(cx).id(),
3413 path: relative_path.into(),
3414 });
3415 }
3416 }
3417
3418 for worktree in worktree_store.visible_worktrees(cx) {
3419 let worktree = worktree.read(cx);
3420 if let Some(entry) = worktree.entry_for_path(path) {
3421 return Some(ProjectPath {
3422 worktree_id: worktree.id(),
3423 path: entry.path.clone(),
3424 });
3425 }
3426 }
3427
3428 None
3429 }
3430
3431 pub fn get_workspace_root(
3432 &self,
3433 project_path: &ProjectPath,
3434 cx: &AppContext,
3435 ) -> Option<PathBuf> {
3436 Some(
3437 self.worktree_for_id(project_path.worktree_id, cx)?
3438 .read(cx)
3439 .abs_path()
3440 .to_path_buf(),
3441 )
3442 }
3443
3444 pub fn get_repo(
3445 &self,
3446 project_path: &ProjectPath,
3447 cx: &AppContext,
3448 ) -> Option<Arc<dyn GitRepository>> {
3449 self.worktree_for_id(project_path.worktree_id, cx)?
3450 .read(cx)
3451 .as_local()?
3452 .local_git_repo(&project_path.path)
3453 }
3454
3455 pub fn get_first_worktree_root_repo(&self, cx: &AppContext) -> Option<Arc<dyn GitRepository>> {
3456 let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
3457 let root_entry = worktree.root_git_entry()?;
3458 worktree.get_local_repo(&root_entry)?.repo().clone().into()
3459 }
3460
3461 pub fn blame_buffer(
3462 &self,
3463 buffer: &Model<Buffer>,
3464 version: Option<clock::Global>,
3465 cx: &AppContext,
3466 ) -> Task<Result<Blame>> {
3467 self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
3468 }
3469
3470 pub fn get_permalink_to_line(
3471 &self,
3472 buffer: &Model<Buffer>,
3473 selection: Range<u32>,
3474 cx: &AppContext,
3475 ) -> Task<Result<url::Url>> {
3476 self.buffer_store
3477 .read(cx)
3478 .get_permalink_to_line(buffer, selection, cx)
3479 }
3480
3481 // RPC message handlers
3482
3483 async fn handle_unshare_project(
3484 this: Model<Self>,
3485 _: TypedEnvelope<proto::UnshareProject>,
3486 mut cx: AsyncAppContext,
3487 ) -> Result<()> {
3488 this.update(&mut cx, |this, cx| {
3489 if this.is_local() || this.is_via_ssh() {
3490 this.unshare(cx)?;
3491 } else {
3492 this.disconnected_from_host(cx);
3493 }
3494 Ok(())
3495 })?
3496 }
3497
3498 async fn handle_add_collaborator(
3499 this: Model<Self>,
3500 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
3501 mut cx: AsyncAppContext,
3502 ) -> Result<()> {
3503 let collaborator = envelope
3504 .payload
3505 .collaborator
3506 .take()
3507 .ok_or_else(|| anyhow!("empty collaborator"))?;
3508
3509 let collaborator = Collaborator::from_proto(collaborator)?;
3510 this.update(&mut cx, |this, cx| {
3511 this.buffer_store.update(cx, |buffer_store, _| {
3512 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
3513 });
3514 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
3515 this.collaborators
3516 .insert(collaborator.peer_id, collaborator);
3517 cx.notify();
3518 })?;
3519
3520 Ok(())
3521 }
3522
3523 async fn handle_update_project_collaborator(
3524 this: Model<Self>,
3525 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
3526 mut cx: AsyncAppContext,
3527 ) -> Result<()> {
3528 let old_peer_id = envelope
3529 .payload
3530 .old_peer_id
3531 .ok_or_else(|| anyhow!("missing old peer id"))?;
3532 let new_peer_id = envelope
3533 .payload
3534 .new_peer_id
3535 .ok_or_else(|| anyhow!("missing new peer id"))?;
3536 this.update(&mut cx, |this, cx| {
3537 let collaborator = this
3538 .collaborators
3539 .remove(&old_peer_id)
3540 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
3541 let is_host = collaborator.replica_id == 0;
3542 this.collaborators.insert(new_peer_id, collaborator);
3543
3544 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
3545 this.buffer_store.update(cx, |buffer_store, _| {
3546 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
3547 });
3548
3549 if is_host {
3550 this.buffer_store
3551 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
3552 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
3553 .unwrap();
3554 cx.emit(Event::HostReshared);
3555 }
3556
3557 cx.emit(Event::CollaboratorUpdated {
3558 old_peer_id,
3559 new_peer_id,
3560 });
3561 cx.notify();
3562 Ok(())
3563 })?
3564 }
3565
3566 async fn handle_remove_collaborator(
3567 this: Model<Self>,
3568 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
3569 mut cx: AsyncAppContext,
3570 ) -> Result<()> {
3571 this.update(&mut cx, |this, cx| {
3572 let peer_id = envelope
3573 .payload
3574 .peer_id
3575 .ok_or_else(|| anyhow!("invalid peer id"))?;
3576 let replica_id = this
3577 .collaborators
3578 .remove(&peer_id)
3579 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
3580 .replica_id;
3581 this.buffer_store.update(cx, |buffer_store, cx| {
3582 buffer_store.forget_shared_buffers_for(&peer_id);
3583 for buffer in buffer_store.buffers() {
3584 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
3585 }
3586 });
3587
3588 cx.emit(Event::CollaboratorLeft(peer_id));
3589 cx.notify();
3590 Ok(())
3591 })?
3592 }
3593
3594 async fn handle_update_project(
3595 this: Model<Self>,
3596 envelope: TypedEnvelope<proto::UpdateProject>,
3597 mut cx: AsyncAppContext,
3598 ) -> Result<()> {
3599 this.update(&mut cx, |this, cx| {
3600 // Don't handle messages that were sent before the response to us joining the project
3601 if envelope.message_id > this.join_project_response_message_id {
3602 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
3603 }
3604 Ok(())
3605 })?
3606 }
3607
3608 async fn handle_toast(
3609 this: Model<Self>,
3610 envelope: TypedEnvelope<proto::Toast>,
3611 mut cx: AsyncAppContext,
3612 ) -> Result<()> {
3613 this.update(&mut cx, |_, cx| {
3614 cx.emit(Event::Toast {
3615 notification_id: envelope.payload.notification_id.into(),
3616 message: envelope.payload.message,
3617 });
3618 Ok(())
3619 })?
3620 }
3621
3622 async fn handle_hide_toast(
3623 this: Model<Self>,
3624 envelope: TypedEnvelope<proto::HideToast>,
3625 mut cx: AsyncAppContext,
3626 ) -> Result<()> {
3627 this.update(&mut cx, |_, cx| {
3628 cx.emit(Event::HideToast {
3629 notification_id: envelope.payload.notification_id.into(),
3630 });
3631 Ok(())
3632 })?
3633 }
3634
3635 // Collab sends UpdateWorktree protos as messages
3636 async fn handle_update_worktree(
3637 this: Model<Self>,
3638 envelope: TypedEnvelope<proto::UpdateWorktree>,
3639 mut cx: AsyncAppContext,
3640 ) -> Result<()> {
3641 this.update(&mut cx, |this, cx| {
3642 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3643 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
3644 worktree.update(cx, |worktree, _| {
3645 let worktree = worktree.as_remote_mut().unwrap();
3646 worktree.update_from_remote(envelope.payload);
3647 });
3648 }
3649 Ok(())
3650 })?
3651 }
3652
3653 async fn handle_update_buffer(
3654 this: Model<Self>,
3655 envelope: TypedEnvelope<proto::UpdateBuffer>,
3656 cx: AsyncAppContext,
3657 ) -> Result<proto::Ack> {
3658 let buffer_store = this.read_with(&cx, |this, cx| {
3659 if let Some(ssh) = &this.ssh_client {
3660 let mut payload = envelope.payload.clone();
3661 payload.project_id = SSH_PROJECT_ID;
3662 cx.background_executor()
3663 .spawn(ssh.read(cx).proto_client().request(payload))
3664 .detach_and_log_err(cx);
3665 }
3666 this.buffer_store.clone()
3667 })?;
3668 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3669 }
3670
3671 fn retain_remotely_created_models(
3672 &mut self,
3673 cx: &mut ModelContext<Self>,
3674 ) -> RemotelyCreatedModelGuard {
3675 {
3676 let mut remotely_create_models = self.remotely_created_models.lock();
3677 if remotely_create_models.retain_count == 0 {
3678 remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
3679 remotely_create_models.worktrees =
3680 self.worktree_store.read(cx).worktrees().collect();
3681 }
3682 remotely_create_models.retain_count += 1;
3683 }
3684 RemotelyCreatedModelGuard {
3685 remote_models: Arc::downgrade(&self.remotely_created_models),
3686 }
3687 }
3688
3689 async fn handle_create_buffer_for_peer(
3690 this: Model<Self>,
3691 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
3692 mut cx: AsyncAppContext,
3693 ) -> Result<()> {
3694 this.update(&mut cx, |this, cx| {
3695 this.buffer_store.update(cx, |buffer_store, cx| {
3696 buffer_store.handle_create_buffer_for_peer(
3697 envelope,
3698 this.replica_id(),
3699 this.capability(),
3700 cx,
3701 )
3702 })
3703 })?
3704 }
3705
3706 async fn handle_synchronize_buffers(
3707 this: Model<Self>,
3708 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
3709 mut cx: AsyncAppContext,
3710 ) -> Result<proto::SynchronizeBuffersResponse> {
3711 let response = this.update(&mut cx, |this, cx| {
3712 let client = this.client.clone();
3713 this.buffer_store.update(cx, |this, cx| {
3714 this.handle_synchronize_buffers(envelope, cx, client)
3715 })
3716 })??;
3717
3718 Ok(response)
3719 }
3720
3721 async fn handle_search_candidate_buffers(
3722 this: Model<Self>,
3723 envelope: TypedEnvelope<proto::FindSearchCandidates>,
3724 mut cx: AsyncAppContext,
3725 ) -> Result<proto::FindSearchCandidatesResponse> {
3726 let peer_id = envelope.original_sender_id()?;
3727 let message = envelope.payload;
3728 let query = SearchQuery::from_proto(
3729 message
3730 .query
3731 .ok_or_else(|| anyhow!("missing query field"))?,
3732 )?;
3733 let mut results = this.update(&mut cx, |this, cx| {
3734 this.find_search_candidate_buffers(&query, message.limit as _, cx)
3735 })?;
3736
3737 let mut response = proto::FindSearchCandidatesResponse {
3738 buffer_ids: Vec::new(),
3739 };
3740
3741 while let Some(buffer) = results.next().await {
3742 this.update(&mut cx, |this, cx| {
3743 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
3744 response.buffer_ids.push(buffer_id.to_proto());
3745 })?;
3746 }
3747
3748 Ok(response)
3749 }
3750
3751 async fn handle_open_buffer_by_id(
3752 this: Model<Self>,
3753 envelope: TypedEnvelope<proto::OpenBufferById>,
3754 mut cx: AsyncAppContext,
3755 ) -> Result<proto::OpenBufferResponse> {
3756 let peer_id = envelope.original_sender_id()?;
3757 let buffer_id = BufferId::new(envelope.payload.id)?;
3758 let buffer = this
3759 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
3760 .await?;
3761 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3762 }
3763
3764 async fn handle_open_buffer_by_path(
3765 this: Model<Self>,
3766 envelope: TypedEnvelope<proto::OpenBufferByPath>,
3767 mut cx: AsyncAppContext,
3768 ) -> Result<proto::OpenBufferResponse> {
3769 let peer_id = envelope.original_sender_id()?;
3770 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3771 let open_buffer = this.update(&mut cx, |this, cx| {
3772 this.open_buffer(
3773 ProjectPath {
3774 worktree_id,
3775 path: PathBuf::from(envelope.payload.path).into(),
3776 },
3777 cx,
3778 )
3779 })?;
3780
3781 let buffer = open_buffer.await?;
3782 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3783 }
3784
3785 async fn handle_open_new_buffer(
3786 this: Model<Self>,
3787 envelope: TypedEnvelope<proto::OpenNewBuffer>,
3788 mut cx: AsyncAppContext,
3789 ) -> Result<proto::OpenBufferResponse> {
3790 let buffer = this
3791 .update(&mut cx, |this, cx| this.create_buffer(cx))?
3792 .await?;
3793 let peer_id = envelope.original_sender_id()?;
3794
3795 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3796 }
3797
3798 fn respond_to_open_buffer_request(
3799 this: Model<Self>,
3800 buffer: Model<Buffer>,
3801 peer_id: proto::PeerId,
3802 cx: &mut AsyncAppContext,
3803 ) -> Result<proto::OpenBufferResponse> {
3804 this.update(cx, |this, cx| {
3805 let is_private = buffer
3806 .read(cx)
3807 .file()
3808 .map(|f| f.is_private())
3809 .unwrap_or_default();
3810 if is_private {
3811 Err(anyhow!(ErrorCode::UnsharedItem))
3812 } else {
3813 Ok(proto::OpenBufferResponse {
3814 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
3815 })
3816 }
3817 })?
3818 }
3819
3820 fn create_buffer_for_peer(
3821 &mut self,
3822 buffer: &Model<Buffer>,
3823 peer_id: proto::PeerId,
3824 cx: &mut AppContext,
3825 ) -> BufferId {
3826 self.buffer_store
3827 .update(cx, |buffer_store, cx| {
3828 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
3829 })
3830 .detach_and_log_err(cx);
3831 buffer.read(cx).remote_id()
3832 }
3833
3834 fn wait_for_remote_buffer(
3835 &mut self,
3836 id: BufferId,
3837 cx: &mut ModelContext<Self>,
3838 ) -> Task<Result<Model<Buffer>>> {
3839 self.buffer_store.update(cx, |buffer_store, cx| {
3840 buffer_store.wait_for_remote_buffer(id, cx)
3841 })
3842 }
3843
3844 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
3845 let project_id = match self.client_state {
3846 ProjectClientState::Remote {
3847 sharing_has_stopped,
3848 remote_id,
3849 ..
3850 } => {
3851 if sharing_has_stopped {
3852 return Task::ready(Err(anyhow!(
3853 "can't synchronize remote buffers on a readonly project"
3854 )));
3855 } else {
3856 remote_id
3857 }
3858 }
3859 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
3860 return Task::ready(Err(anyhow!(
3861 "can't synchronize remote buffers on a local project"
3862 )))
3863 }
3864 };
3865
3866 let client = self.client.clone();
3867 cx.spawn(move |this, mut cx| async move {
3868 let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
3869 this.buffer_store.read(cx).buffer_version_info(cx)
3870 })?;
3871 let response = client
3872 .request(proto::SynchronizeBuffers {
3873 project_id,
3874 buffers,
3875 })
3876 .await?;
3877
3878 let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
3879 response
3880 .buffers
3881 .into_iter()
3882 .map(|buffer| {
3883 let client = client.clone();
3884 let buffer_id = match BufferId::new(buffer.id) {
3885 Ok(id) => id,
3886 Err(e) => {
3887 return Task::ready(Err(e));
3888 }
3889 };
3890 let remote_version = language::proto::deserialize_version(&buffer.version);
3891 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
3892 let operations =
3893 buffer.read(cx).serialize_ops(Some(remote_version), cx);
3894 cx.background_executor().spawn(async move {
3895 let operations = operations.await;
3896 for chunk in split_operations(operations) {
3897 client
3898 .request(proto::UpdateBuffer {
3899 project_id,
3900 buffer_id: buffer_id.into(),
3901 operations: chunk,
3902 })
3903 .await?;
3904 }
3905 anyhow::Ok(())
3906 })
3907 } else {
3908 Task::ready(Ok(()))
3909 }
3910 })
3911 .collect::<Vec<_>>()
3912 })?;
3913
3914 // Any incomplete buffers have open requests waiting. Request that the host sends
3915 // creates these buffers for us again to unblock any waiting futures.
3916 for id in incomplete_buffer_ids {
3917 cx.background_executor()
3918 .spawn(client.request(proto::OpenBufferById {
3919 project_id,
3920 id: id.into(),
3921 }))
3922 .detach();
3923 }
3924
3925 futures::future::join_all(send_updates_for_buffers)
3926 .await
3927 .into_iter()
3928 .collect()
3929 })
3930 }
3931
3932 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
3933 self.worktree_store.read(cx).worktree_metadata_protos(cx)
3934 }
3935
3936 fn set_worktrees_from_proto(
3937 &mut self,
3938 worktrees: Vec<proto::WorktreeMetadata>,
3939 cx: &mut ModelContext<Project>,
3940 ) -> Result<()> {
3941 cx.notify();
3942 self.worktree_store.update(cx, |worktree_store, cx| {
3943 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
3944 })
3945 }
3946
3947 fn set_collaborators_from_proto(
3948 &mut self,
3949 messages: Vec<proto::Collaborator>,
3950 cx: &mut ModelContext<Self>,
3951 ) -> Result<()> {
3952 let mut collaborators = HashMap::default();
3953 for message in messages {
3954 let collaborator = Collaborator::from_proto(message)?;
3955 collaborators.insert(collaborator.peer_id, collaborator);
3956 }
3957 for old_peer_id in self.collaborators.keys() {
3958 if !collaborators.contains_key(old_peer_id) {
3959 cx.emit(Event::CollaboratorLeft(*old_peer_id));
3960 }
3961 }
3962 self.collaborators = collaborators;
3963 Ok(())
3964 }
3965
3966 pub fn language_servers<'a>(
3967 &'a self,
3968 cx: &'a AppContext,
3969 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
3970 self.lsp_store.read(cx).language_servers()
3971 }
3972
3973 pub fn supplementary_language_servers<'a>(
3974 &'a self,
3975 cx: &'a AppContext,
3976 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
3977 self.lsp_store.read(cx).supplementary_language_servers()
3978 }
3979
3980 pub fn language_server_for_id(
3981 &self,
3982 id: LanguageServerId,
3983 cx: &AppContext,
3984 ) -> Option<Arc<LanguageServer>> {
3985 self.lsp_store.read(cx).language_server_for_id(id)
3986 }
3987
3988 pub fn language_servers_for_buffer<'a>(
3989 &'a self,
3990 buffer: &'a Buffer,
3991 cx: &'a AppContext,
3992 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
3993 self.lsp_store
3994 .read(cx)
3995 .language_servers_for_buffer(buffer, cx)
3996 }
3997}
3998
3999fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
4000 code_actions
4001 .iter()
4002 .flat_map(|(kind, enabled)| {
4003 if *enabled {
4004 Some(kind.clone().into())
4005 } else {
4006 None
4007 }
4008 })
4009 .collect()
4010}
4011
4012pub struct PathMatchCandidateSet {
4013 pub snapshot: Snapshot,
4014 pub include_ignored: bool,
4015 pub include_root_name: bool,
4016 pub candidates: Candidates,
4017}
4018
4019pub enum Candidates {
4020 /// Only consider directories.
4021 Directories,
4022 /// Only consider files.
4023 Files,
4024 /// Consider directories and files.
4025 Entries,
4026}
4027
4028impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4029 type Candidates = PathMatchCandidateSetIter<'a>;
4030
4031 fn id(&self) -> usize {
4032 self.snapshot.id().to_usize()
4033 }
4034
4035 fn len(&self) -> usize {
4036 match self.candidates {
4037 Candidates::Files => {
4038 if self.include_ignored {
4039 self.snapshot.file_count()
4040 } else {
4041 self.snapshot.visible_file_count()
4042 }
4043 }
4044
4045 Candidates::Directories => {
4046 if self.include_ignored {
4047 self.snapshot.dir_count()
4048 } else {
4049 self.snapshot.visible_dir_count()
4050 }
4051 }
4052
4053 Candidates::Entries => {
4054 if self.include_ignored {
4055 self.snapshot.entry_count()
4056 } else {
4057 self.snapshot.visible_entry_count()
4058 }
4059 }
4060 }
4061 }
4062
4063 fn prefix(&self) -> Arc<str> {
4064 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
4065 self.snapshot.root_name().into()
4066 } else if self.include_root_name {
4067 format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
4068 } else {
4069 Arc::default()
4070 }
4071 }
4072
4073 fn candidates(&'a self, start: usize) -> Self::Candidates {
4074 PathMatchCandidateSetIter {
4075 traversal: match self.candidates {
4076 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
4077 Candidates::Files => self.snapshot.files(self.include_ignored, start),
4078 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
4079 },
4080 }
4081 }
4082}
4083
4084pub struct PathMatchCandidateSetIter<'a> {
4085 traversal: Traversal<'a>,
4086}
4087
4088impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
4089 type Item = fuzzy::PathMatchCandidate<'a>;
4090
4091 fn next(&mut self) -> Option<Self::Item> {
4092 self.traversal
4093 .next()
4094 .map(|entry| fuzzy::PathMatchCandidate {
4095 is_dir: entry.kind.is_dir(),
4096 path: &entry.path,
4097 char_bag: entry.char_bag,
4098 })
4099 }
4100}
4101
4102impl EventEmitter<Event> for Project {}
4103
4104impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
4105 fn from(val: &'a ProjectPath) -> Self {
4106 SettingsLocation {
4107 worktree_id: val.worktree_id,
4108 path: val.path.as_ref(),
4109 }
4110 }
4111}
4112
4113impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
4114 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
4115 Self {
4116 worktree_id,
4117 path: path.as_ref().into(),
4118 }
4119 }
4120}
4121
4122pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
4123 let mut path_components = path.components();
4124 let mut base_components = base.components();
4125 let mut components: Vec<Component> = Vec::new();
4126 loop {
4127 match (path_components.next(), base_components.next()) {
4128 (None, None) => break,
4129 (Some(a), None) => {
4130 components.push(a);
4131 components.extend(path_components.by_ref());
4132 break;
4133 }
4134 (None, _) => components.push(Component::ParentDir),
4135 (Some(a), Some(b)) if components.is_empty() && a == b => (),
4136 (Some(a), Some(Component::CurDir)) => components.push(a),
4137 (Some(a), Some(_)) => {
4138 components.push(Component::ParentDir);
4139 for _ in base_components {
4140 components.push(Component::ParentDir);
4141 }
4142 components.push(a);
4143 components.extend(path_components.by_ref());
4144 break;
4145 }
4146 }
4147 }
4148 components.iter().map(|c| c.as_os_str()).collect()
4149}
4150
4151fn resolve_path(base: &Path, path: &Path) -> PathBuf {
4152 let mut result = base.to_path_buf();
4153 for component in path.components() {
4154 match component {
4155 Component::ParentDir => {
4156 result.pop();
4157 }
4158 Component::CurDir => (),
4159 _ => result.push(component),
4160 }
4161 }
4162 result
4163}
4164
4165/// ResolvedPath is a path that has been resolved to either a ProjectPath
4166/// or an AbsPath and that *exists*.
4167#[derive(Debug, Clone)]
4168pub enum ResolvedPath {
4169 ProjectPath(ProjectPath),
4170 AbsPath(PathBuf),
4171}
4172
4173impl ResolvedPath {
4174 pub fn abs_path(&self) -> Option<&Path> {
4175 match self {
4176 Self::AbsPath(path) => Some(path.as_path()),
4177 _ => None,
4178 }
4179 }
4180
4181 pub fn project_path(&self) -> Option<&ProjectPath> {
4182 match self {
4183 Self::ProjectPath(path) => Some(&path),
4184 _ => None,
4185 }
4186 }
4187}
4188
4189impl Item for Buffer {
4190 fn try_open(
4191 project: &Model<Project>,
4192 path: &ProjectPath,
4193 cx: &mut AppContext,
4194 ) -> Option<Task<Result<Model<Self>>>> {
4195 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
4196 }
4197
4198 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
4199 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
4200 }
4201
4202 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
4203 File::from_dyn(self.file()).map(|file| ProjectPath {
4204 worktree_id: file.worktree_id(cx),
4205 path: file.path().clone(),
4206 })
4207 }
4208}
4209
4210impl Completion {
4211 /// A key that can be used to sort completions when displaying
4212 /// them to the user.
4213 pub fn sort_key(&self) -> (usize, &str) {
4214 let kind_key = match self.lsp_completion.kind {
4215 Some(lsp::CompletionItemKind::KEYWORD) => 0,
4216 Some(lsp::CompletionItemKind::VARIABLE) => 1,
4217 _ => 2,
4218 };
4219 (kind_key, &self.label.text[self.label.filter_range.clone()])
4220 }
4221
4222 /// Whether this completion is a snippet.
4223 pub fn is_snippet(&self) -> bool {
4224 self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
4225 }
4226
4227 /// Returns the corresponding color for this completion.
4228 ///
4229 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
4230 pub fn color(&self) -> Option<Hsla> {
4231 match self.lsp_completion.kind {
4232 Some(CompletionItemKind::COLOR) => color_extractor::extract_color(&self.lsp_completion),
4233 _ => None,
4234 }
4235 }
4236}
4237
4238#[derive(Debug)]
4239pub struct NoRepositoryError {}
4240
4241impl std::fmt::Display for NoRepositoryError {
4242 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4243 write!(f, "no git repository for worktree found")
4244 }
4245}
4246
4247impl std::error::Error for NoRepositoryError {}
4248
4249pub fn sort_worktree_entries(entries: &mut [Entry]) {
4250 entries.sort_by(|entry_a, entry_b| {
4251 compare_paths(
4252 (&entry_a.path, entry_a.is_file()),
4253 (&entry_b.path, entry_b.is_file()),
4254 )
4255 });
4256}