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 user_store(&self) -> Model<UserStore> {
1247 self.user_store.clone()
1248 }
1249
1250 pub fn node_runtime(&self) -> Option<&NodeRuntime> {
1251 self.node.as_ref()
1252 }
1253
1254 pub fn opened_buffers(&self, cx: &AppContext) -> Vec<Model<Buffer>> {
1255 self.buffer_store.read(cx).buffers().collect()
1256 }
1257
1258 pub fn cli_environment(&self, cx: &AppContext) -> Option<HashMap<String, String>> {
1259 self.environment.read(cx).get_cli_environment()
1260 }
1261
1262 pub fn shell_environment_errors<'a>(
1263 &'a self,
1264 cx: &'a AppContext,
1265 ) -> impl Iterator<Item = (&'a WorktreeId, &'a EnvironmentErrorMessage)> {
1266 self.environment.read(cx).environment_errors()
1267 }
1268
1269 pub fn remove_environment_error(
1270 &mut self,
1271 cx: &mut ModelContext<Self>,
1272 worktree_id: WorktreeId,
1273 ) {
1274 self.environment.update(cx, |environment, _| {
1275 environment.remove_environment_error(worktree_id);
1276 });
1277 }
1278
1279 #[cfg(any(test, feature = "test-support"))]
1280 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
1281 self.buffer_store
1282 .read(cx)
1283 .get_by_path(&path.into(), cx)
1284 .is_some()
1285 }
1286
1287 pub fn fs(&self) -> &Arc<dyn Fs> {
1288 &self.fs
1289 }
1290
1291 pub fn remote_id(&self) -> Option<u64> {
1292 match self.client_state {
1293 ProjectClientState::Local => None,
1294 ProjectClientState::Shared { remote_id, .. }
1295 | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1296 }
1297 }
1298
1299 pub fn hosted_project_id(&self) -> Option<ProjectId> {
1300 self.hosted_project_id
1301 }
1302
1303 pub fn dev_server_project_id(&self) -> Option<DevServerProjectId> {
1304 self.dev_server_project_id
1305 }
1306
1307 pub fn supports_terminal(&self, cx: &AppContext) -> bool {
1308 if self.is_local() {
1309 return true;
1310 }
1311 if self.is_via_ssh() {
1312 return true;
1313 }
1314 let Some(id) = self.dev_server_project_id else {
1315 return false;
1316 };
1317 let Some(server) = dev_server_projects::Store::global(cx)
1318 .read(cx)
1319 .dev_server_for_project(id)
1320 else {
1321 return false;
1322 };
1323 server.ssh_connection_string.is_some()
1324 }
1325
1326 pub fn ssh_connection_string(&self, cx: &AppContext) -> Option<SharedString> {
1327 if let Some(ssh_state) = &self.ssh_client {
1328 return Some(ssh_state.read(cx).connection_string().into());
1329 }
1330 let dev_server_id = self.dev_server_project_id()?;
1331 dev_server_projects::Store::global(cx)
1332 .read(cx)
1333 .dev_server_for_project(dev_server_id)?
1334 .ssh_connection_string
1335 .clone()
1336 }
1337
1338 pub fn ssh_connection_state(&self, cx: &AppContext) -> Option<remote::ConnectionState> {
1339 self.ssh_client
1340 .as_ref()
1341 .map(|ssh| ssh.read(cx).connection_state())
1342 }
1343
1344 pub fn ssh_connection_options(&self, cx: &AppContext) -> Option<SshConnectionOptions> {
1345 self.ssh_client
1346 .as_ref()
1347 .map(|ssh| ssh.read(cx).connection_options())
1348 }
1349
1350 pub fn replica_id(&self) -> ReplicaId {
1351 match self.client_state {
1352 ProjectClientState::Remote { replica_id, .. } => replica_id,
1353 _ => {
1354 if self.ssh_client.is_some() {
1355 1
1356 } else {
1357 0
1358 }
1359 }
1360 }
1361 }
1362
1363 pub fn task_store(&self) -> &Model<TaskStore> {
1364 &self.task_store
1365 }
1366
1367 pub fn snippets(&self) -> &Model<SnippetProvider> {
1368 &self.snippets
1369 }
1370
1371 pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1372 match kind {
1373 SearchInputKind::Query => &self.search_history,
1374 SearchInputKind::Include => &self.search_included_history,
1375 SearchInputKind::Exclude => &self.search_excluded_history,
1376 }
1377 }
1378
1379 pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1380 match kind {
1381 SearchInputKind::Query => &mut self.search_history,
1382 SearchInputKind::Include => &mut self.search_included_history,
1383 SearchInputKind::Exclude => &mut self.search_excluded_history,
1384 }
1385 }
1386
1387 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1388 &self.collaborators
1389 }
1390
1391 pub fn host(&self) -> Option<&Collaborator> {
1392 self.collaborators.values().find(|c| c.replica_id == 0)
1393 }
1394
1395 pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut AppContext) {
1396 self.worktree_store.update(cx, |store, _| {
1397 store.set_worktrees_reordered(worktrees_reordered);
1398 });
1399 }
1400
1401 /// Collect all worktrees, including ones that don't appear in the project panel
1402 pub fn worktrees<'a>(
1403 &self,
1404 cx: &'a AppContext,
1405 ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1406 self.worktree_store.read(cx).worktrees()
1407 }
1408
1409 /// Collect all user-visible worktrees, the ones that appear in the project panel.
1410 pub fn visible_worktrees<'a>(
1411 &'a self,
1412 cx: &'a AppContext,
1413 ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1414 self.worktree_store.read(cx).visible_worktrees(cx)
1415 }
1416
1417 pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1418 self.visible_worktrees(cx)
1419 .map(|tree| tree.read(cx).root_name())
1420 }
1421
1422 pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
1423 self.worktree_store.read(cx).worktree_for_id(id, cx)
1424 }
1425
1426 pub fn worktree_for_entry(
1427 &self,
1428 entry_id: ProjectEntryId,
1429 cx: &AppContext,
1430 ) -> Option<Model<Worktree>> {
1431 self.worktree_store
1432 .read(cx)
1433 .worktree_for_entry(entry_id, cx)
1434 }
1435
1436 pub fn worktree_id_for_entry(
1437 &self,
1438 entry_id: ProjectEntryId,
1439 cx: &AppContext,
1440 ) -> Option<WorktreeId> {
1441 self.worktree_for_entry(entry_id, cx)
1442 .map(|worktree| worktree.read(cx).id())
1443 }
1444
1445 /// Checks if the entry is the root of a worktree.
1446 pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &AppContext) -> bool {
1447 self.worktree_for_entry(entry_id, cx)
1448 .map(|worktree| {
1449 worktree
1450 .read(cx)
1451 .root_entry()
1452 .is_some_and(|e| e.id == entry_id)
1453 })
1454 .unwrap_or(false)
1455 }
1456
1457 pub fn visibility_for_paths(&self, paths: &[PathBuf], cx: &AppContext) -> Option<bool> {
1458 paths
1459 .iter()
1460 .map(|path| self.visibility_for_path(path, cx))
1461 .max()
1462 .flatten()
1463 }
1464
1465 pub fn visibility_for_path(&self, path: &Path, cx: &AppContext) -> Option<bool> {
1466 self.worktrees(cx)
1467 .filter_map(|worktree| {
1468 let worktree = worktree.read(cx);
1469 worktree
1470 .as_local()?
1471 .contains_abs_path(path)
1472 .then(|| worktree.is_visible())
1473 })
1474 .max()
1475 }
1476
1477 pub fn create_entry(
1478 &mut self,
1479 project_path: impl Into<ProjectPath>,
1480 is_directory: bool,
1481 cx: &mut ModelContext<Self>,
1482 ) -> Task<Result<CreatedEntry>> {
1483 let project_path = project_path.into();
1484 let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1485 return Task::ready(Err(anyhow!(format!(
1486 "No worktree for path {project_path:?}"
1487 ))));
1488 };
1489 worktree.update(cx, |worktree, cx| {
1490 worktree.create_entry(project_path.path, is_directory, cx)
1491 })
1492 }
1493
1494 pub fn copy_entry(
1495 &mut self,
1496 entry_id: ProjectEntryId,
1497 relative_worktree_source_path: Option<PathBuf>,
1498 new_path: impl Into<Arc<Path>>,
1499 cx: &mut ModelContext<Self>,
1500 ) -> Task<Result<Option<Entry>>> {
1501 let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1502 return Task::ready(Ok(None));
1503 };
1504 worktree.update(cx, |worktree, cx| {
1505 worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1506 })
1507 }
1508
1509 pub fn rename_entry(
1510 &mut self,
1511 entry_id: ProjectEntryId,
1512 new_path: impl Into<Arc<Path>>,
1513 cx: &mut ModelContext<Self>,
1514 ) -> Task<Result<CreatedEntry>> {
1515 let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1516 return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1517 };
1518 worktree.update(cx, |worktree, cx| {
1519 worktree.rename_entry(entry_id, new_path, cx)
1520 })
1521 }
1522
1523 pub fn delete_entry(
1524 &mut self,
1525 entry_id: ProjectEntryId,
1526 trash: bool,
1527 cx: &mut ModelContext<Self>,
1528 ) -> Option<Task<Result<()>>> {
1529 let worktree = self.worktree_for_entry(entry_id, cx)?;
1530 worktree.update(cx, |worktree, cx| {
1531 worktree.delete_entry(entry_id, trash, cx)
1532 })
1533 }
1534
1535 pub fn expand_entry(
1536 &mut self,
1537 worktree_id: WorktreeId,
1538 entry_id: ProjectEntryId,
1539 cx: &mut ModelContext<Self>,
1540 ) -> Option<Task<Result<()>>> {
1541 let worktree = self.worktree_for_id(worktree_id, cx)?;
1542 worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
1543 }
1544
1545 pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
1546 if !matches!(self.client_state, ProjectClientState::Local) {
1547 if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
1548 if *in_room || self.dev_server_project_id.is_none() {
1549 return Err(anyhow!("project was already shared"));
1550 } else {
1551 *in_room = true;
1552 return Ok(());
1553 }
1554 } else {
1555 return Err(anyhow!("project was already shared"));
1556 }
1557 }
1558 self.client_subscriptions.extend([
1559 self.client
1560 .subscribe_to_entity(project_id)?
1561 .set_model(&cx.handle(), &mut cx.to_async()),
1562 self.client
1563 .subscribe_to_entity(project_id)?
1564 .set_model(&self.worktree_store, &mut cx.to_async()),
1565 self.client
1566 .subscribe_to_entity(project_id)?
1567 .set_model(&self.buffer_store, &mut cx.to_async()),
1568 self.client
1569 .subscribe_to_entity(project_id)?
1570 .set_model(&self.lsp_store, &mut cx.to_async()),
1571 self.client
1572 .subscribe_to_entity(project_id)?
1573 .set_model(&self.settings_observer, &mut cx.to_async()),
1574 ]);
1575
1576 self.buffer_store.update(cx, |buffer_store, cx| {
1577 buffer_store.shared(project_id, self.client.clone().into(), cx)
1578 });
1579 self.worktree_store.update(cx, |worktree_store, cx| {
1580 worktree_store.shared(project_id, self.client.clone().into(), cx);
1581 });
1582 self.lsp_store.update(cx, |lsp_store, cx| {
1583 lsp_store.shared(project_id, self.client.clone().into(), cx)
1584 });
1585 self.task_store.update(cx, |task_store, cx| {
1586 task_store.shared(project_id, self.client.clone().into(), cx);
1587 });
1588 self.settings_observer.update(cx, |settings_observer, cx| {
1589 settings_observer.shared(project_id, self.client.clone().into(), cx)
1590 });
1591
1592 self.client_state = ProjectClientState::Shared {
1593 remote_id: project_id,
1594 };
1595
1596 cx.emit(Event::RemoteIdChanged(Some(project_id)));
1597 cx.notify();
1598 Ok(())
1599 }
1600
1601 pub fn reshared(
1602 &mut self,
1603 message: proto::ResharedProject,
1604 cx: &mut ModelContext<Self>,
1605 ) -> Result<()> {
1606 self.buffer_store
1607 .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
1608 self.set_collaborators_from_proto(message.collaborators, cx)?;
1609
1610 self.worktree_store.update(cx, |worktree_store, cx| {
1611 worktree_store.send_project_updates(cx);
1612 });
1613 cx.notify();
1614 cx.emit(Event::Reshared);
1615 Ok(())
1616 }
1617
1618 pub fn rejoined(
1619 &mut self,
1620 message: proto::RejoinedProject,
1621 message_id: u32,
1622 cx: &mut ModelContext<Self>,
1623 ) -> Result<()> {
1624 cx.update_global::<SettingsStore, _>(|store, cx| {
1625 self.worktree_store.update(cx, |worktree_store, cx| {
1626 for worktree in worktree_store.worktrees() {
1627 store
1628 .clear_local_settings(worktree.read(cx).id(), cx)
1629 .log_err();
1630 }
1631 });
1632 });
1633
1634 self.join_project_response_message_id = message_id;
1635 self.set_worktrees_from_proto(message.worktrees, cx)?;
1636 self.set_collaborators_from_proto(message.collaborators, cx)?;
1637 self.lsp_store.update(cx, |lsp_store, _| {
1638 lsp_store.set_language_server_statuses_from_proto(message.language_servers)
1639 });
1640 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
1641 .unwrap();
1642 cx.emit(Event::Rejoined);
1643 cx.notify();
1644 Ok(())
1645 }
1646
1647 pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1648 self.unshare_internal(cx)?;
1649 cx.notify();
1650 Ok(())
1651 }
1652
1653 fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1654 if self.is_via_collab() {
1655 if self.dev_server_project_id().is_some() {
1656 if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
1657 *in_room = false
1658 }
1659 return Ok(());
1660 } else {
1661 return Err(anyhow!("attempted to unshare a remote project"));
1662 }
1663 }
1664
1665 if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
1666 self.client_state = ProjectClientState::Local;
1667 self.collaborators.clear();
1668 self.client_subscriptions.clear();
1669 self.worktree_store.update(cx, |store, cx| {
1670 store.unshared(cx);
1671 });
1672 self.buffer_store.update(cx, |buffer_store, cx| {
1673 buffer_store.forget_shared_buffers();
1674 buffer_store.unshared(cx)
1675 });
1676 self.task_store.update(cx, |task_store, cx| {
1677 task_store.unshared(cx);
1678 });
1679 self.settings_observer.update(cx, |settings_observer, cx| {
1680 settings_observer.unshared(cx);
1681 });
1682
1683 self.client
1684 .send(proto::UnshareProject {
1685 project_id: remote_id,
1686 })
1687 .ok();
1688 Ok(())
1689 } else {
1690 Err(anyhow!("attempted to unshare an unshared project"))
1691 }
1692 }
1693
1694 pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1695 if self.is_disconnected(cx) {
1696 return;
1697 }
1698 self.disconnected_from_host_internal(cx);
1699 cx.emit(Event::DisconnectedFromHost);
1700 cx.notify();
1701 }
1702
1703 pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut ModelContext<Self>) {
1704 let new_capability =
1705 if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
1706 Capability::ReadWrite
1707 } else {
1708 Capability::ReadOnly
1709 };
1710 if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
1711 if *capability == new_capability {
1712 return;
1713 }
1714
1715 *capability = new_capability;
1716 for buffer in self.opened_buffers(cx) {
1717 buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
1718 }
1719 }
1720 }
1721
1722 fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1723 if let ProjectClientState::Remote {
1724 sharing_has_stopped,
1725 ..
1726 } = &mut self.client_state
1727 {
1728 *sharing_has_stopped = true;
1729 self.collaborators.clear();
1730 self.worktree_store.update(cx, |store, cx| {
1731 store.disconnected_from_host(cx);
1732 });
1733 self.buffer_store.update(cx, |buffer_store, cx| {
1734 buffer_store.disconnected_from_host(cx)
1735 });
1736 self.lsp_store
1737 .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
1738 }
1739 }
1740
1741 pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1742 cx.emit(Event::Closed);
1743 }
1744
1745 pub fn is_disconnected(&self, cx: &AppContext) -> bool {
1746 match &self.client_state {
1747 ProjectClientState::Remote {
1748 sharing_has_stopped,
1749 ..
1750 } => *sharing_has_stopped,
1751 ProjectClientState::Local if self.is_via_ssh() => self.ssh_is_disconnected(cx),
1752 _ => false,
1753 }
1754 }
1755
1756 fn ssh_is_disconnected(&self, cx: &AppContext) -> bool {
1757 self.ssh_client
1758 .as_ref()
1759 .map(|ssh| ssh.read(cx).is_disconnected())
1760 .unwrap_or(false)
1761 }
1762
1763 pub fn capability(&self) -> Capability {
1764 match &self.client_state {
1765 ProjectClientState::Remote { capability, .. } => *capability,
1766 ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
1767 }
1768 }
1769
1770 pub fn is_read_only(&self, cx: &AppContext) -> bool {
1771 self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
1772 }
1773
1774 pub fn is_local(&self) -> bool {
1775 match &self.client_state {
1776 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1777 self.ssh_client.is_none()
1778 }
1779 ProjectClientState::Remote { .. } => false,
1780 }
1781 }
1782
1783 pub fn is_via_ssh(&self) -> bool {
1784 match &self.client_state {
1785 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1786 self.ssh_client.is_some()
1787 }
1788 ProjectClientState::Remote { .. } => false,
1789 }
1790 }
1791
1792 pub fn is_via_collab(&self) -> bool {
1793 match &self.client_state {
1794 ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
1795 ProjectClientState::Remote { .. } => true,
1796 }
1797 }
1798
1799 pub fn create_buffer(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<Model<Buffer>>> {
1800 self.buffer_store
1801 .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx))
1802 }
1803
1804 pub fn create_local_buffer(
1805 &mut self,
1806 text: &str,
1807 language: Option<Arc<Language>>,
1808 cx: &mut ModelContext<Self>,
1809 ) -> Model<Buffer> {
1810 if self.is_via_collab() || self.is_via_ssh() {
1811 panic!("called create_local_buffer on a remote project")
1812 }
1813 self.buffer_store.update(cx, |buffer_store, cx| {
1814 buffer_store.create_local_buffer(text, language, cx)
1815 })
1816 }
1817
1818 pub fn open_path(
1819 &mut self,
1820 path: ProjectPath,
1821 cx: &mut ModelContext<Self>,
1822 ) -> Task<Result<(Option<ProjectEntryId>, AnyModel)>> {
1823 let task = self.open_buffer(path.clone(), cx);
1824 cx.spawn(move |_, cx| async move {
1825 let buffer = task.await?;
1826 let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
1827 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1828 })?;
1829
1830 let buffer: &AnyModel = &buffer;
1831 Ok((project_entry_id, buffer.clone()))
1832 })
1833 }
1834
1835 pub fn open_local_buffer(
1836 &mut self,
1837 abs_path: impl AsRef<Path>,
1838 cx: &mut ModelContext<Self>,
1839 ) -> Task<Result<Model<Buffer>>> {
1840 if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
1841 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1842 } else {
1843 Task::ready(Err(anyhow!("no such path")))
1844 }
1845 }
1846
1847 pub fn open_buffer(
1848 &mut self,
1849 path: impl Into<ProjectPath>,
1850 cx: &mut ModelContext<Self>,
1851 ) -> Task<Result<Model<Buffer>>> {
1852 if (self.is_via_collab() || self.is_via_ssh()) && self.is_disconnected(cx) {
1853 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1854 }
1855
1856 self.buffer_store.update(cx, |buffer_store, cx| {
1857 buffer_store.open_buffer(path.into(), cx)
1858 })
1859 }
1860
1861 pub fn open_buffer_by_id(
1862 &mut self,
1863 id: BufferId,
1864 cx: &mut ModelContext<Self>,
1865 ) -> Task<Result<Model<Buffer>>> {
1866 if let Some(buffer) = self.buffer_for_id(id, cx) {
1867 Task::ready(Ok(buffer))
1868 } else if self.is_local() || self.is_via_ssh() {
1869 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1870 } else if let Some(project_id) = self.remote_id() {
1871 let request = self.client.request(proto::OpenBufferById {
1872 project_id,
1873 id: id.into(),
1874 });
1875 cx.spawn(move |this, mut cx| async move {
1876 let buffer_id = BufferId::new(request.await?.buffer_id)?;
1877 this.update(&mut cx, |this, cx| {
1878 this.wait_for_remote_buffer(buffer_id, cx)
1879 })?
1880 .await
1881 })
1882 } else {
1883 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1884 }
1885 }
1886
1887 pub fn save_buffers(
1888 &self,
1889 buffers: HashSet<Model<Buffer>>,
1890 cx: &mut ModelContext<Self>,
1891 ) -> Task<Result<()>> {
1892 cx.spawn(move |this, mut cx| async move {
1893 let save_tasks = buffers.into_iter().filter_map(|buffer| {
1894 this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
1895 .ok()
1896 });
1897 try_join_all(save_tasks).await?;
1898 Ok(())
1899 })
1900 }
1901
1902 pub fn save_buffer(
1903 &self,
1904 buffer: Model<Buffer>,
1905 cx: &mut ModelContext<Self>,
1906 ) -> Task<Result<()>> {
1907 self.buffer_store
1908 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
1909 }
1910
1911 pub fn save_buffer_as(
1912 &mut self,
1913 buffer: Model<Buffer>,
1914 path: ProjectPath,
1915 cx: &mut ModelContext<Self>,
1916 ) -> Task<Result<()>> {
1917 self.buffer_store.update(cx, |buffer_store, cx| {
1918 buffer_store.save_buffer_as(buffer.clone(), path, cx)
1919 })
1920 }
1921
1922 pub fn get_open_buffer(
1923 &mut self,
1924 path: &ProjectPath,
1925 cx: &mut ModelContext<Self>,
1926 ) -> Option<Model<Buffer>> {
1927 self.buffer_store.read(cx).get_by_path(path, cx)
1928 }
1929
1930 fn register_buffer(
1931 &mut self,
1932 buffer: &Model<Buffer>,
1933 cx: &mut ModelContext<Self>,
1934 ) -> Result<()> {
1935 {
1936 let mut remotely_created_models = self.remotely_created_models.lock();
1937 if remotely_created_models.retain_count > 0 {
1938 remotely_created_models.buffers.push(buffer.clone())
1939 }
1940 }
1941
1942 self.request_buffer_diff_recalculation(buffer, cx);
1943
1944 cx.subscribe(buffer, |this, buffer, event, cx| {
1945 this.on_buffer_event(buffer, event, cx);
1946 })
1947 .detach();
1948
1949 Ok(())
1950 }
1951
1952 async fn send_buffer_ordered_messages(
1953 this: WeakModel<Self>,
1954 rx: UnboundedReceiver<BufferOrderedMessage>,
1955 mut cx: AsyncAppContext,
1956 ) -> Result<()> {
1957 const MAX_BATCH_SIZE: usize = 128;
1958
1959 let mut operations_by_buffer_id = HashMap::default();
1960 async fn flush_operations(
1961 this: &WeakModel<Project>,
1962 operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
1963 needs_resync_with_host: &mut bool,
1964 is_local: bool,
1965 cx: &mut AsyncAppContext,
1966 ) -> Result<()> {
1967 for (buffer_id, operations) in operations_by_buffer_id.drain() {
1968 let request = this.update(cx, |this, _| {
1969 let project_id = this.remote_id()?;
1970 Some(this.client.request(proto::UpdateBuffer {
1971 buffer_id: buffer_id.into(),
1972 project_id,
1973 operations,
1974 }))
1975 })?;
1976 if let Some(request) = request {
1977 if request.await.is_err() && !is_local {
1978 *needs_resync_with_host = true;
1979 break;
1980 }
1981 }
1982 }
1983 Ok(())
1984 }
1985
1986 let mut needs_resync_with_host = false;
1987 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
1988
1989 while let Some(changes) = changes.next().await {
1990 let is_local = this.update(&mut cx, |this, _| this.is_local())?;
1991
1992 for change in changes {
1993 match change {
1994 BufferOrderedMessage::Operation {
1995 buffer_id,
1996 operation,
1997 } => {
1998 if needs_resync_with_host {
1999 continue;
2000 }
2001
2002 operations_by_buffer_id
2003 .entry(buffer_id)
2004 .or_insert(Vec::new())
2005 .push(operation);
2006 }
2007
2008 BufferOrderedMessage::Resync => {
2009 operations_by_buffer_id.clear();
2010 if this
2011 .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
2012 .await
2013 .is_ok()
2014 {
2015 needs_resync_with_host = false;
2016 }
2017 }
2018
2019 BufferOrderedMessage::LanguageServerUpdate {
2020 language_server_id,
2021 message,
2022 } => {
2023 flush_operations(
2024 &this,
2025 &mut operations_by_buffer_id,
2026 &mut needs_resync_with_host,
2027 is_local,
2028 &mut cx,
2029 )
2030 .await?;
2031
2032 this.update(&mut cx, |this, _| {
2033 if let Some(project_id) = this.remote_id() {
2034 this.client
2035 .send(proto::UpdateLanguageServer {
2036 project_id,
2037 language_server_id: language_server_id.0 as u64,
2038 variant: Some(message),
2039 })
2040 .log_err();
2041 }
2042 })?;
2043 }
2044 }
2045 }
2046
2047 flush_operations(
2048 &this,
2049 &mut operations_by_buffer_id,
2050 &mut needs_resync_with_host,
2051 is_local,
2052 &mut cx,
2053 )
2054 .await?;
2055 }
2056
2057 Ok(())
2058 }
2059
2060 fn on_buffer_store_event(
2061 &mut self,
2062 _: Model<BufferStore>,
2063 event: &BufferStoreEvent,
2064 cx: &mut ModelContext<Self>,
2065 ) {
2066 match event {
2067 BufferStoreEvent::BufferAdded(buffer) => {
2068 self.register_buffer(buffer, cx).log_err();
2069 }
2070 BufferStoreEvent::BufferChangedFilePath { .. } => {}
2071 BufferStoreEvent::BufferDropped(buffer_id) => {
2072 if let Some(ref ssh_client) = self.ssh_client {
2073 ssh_client
2074 .read(cx)
2075 .proto_client()
2076 .send(proto::CloseBuffer {
2077 project_id: 0,
2078 buffer_id: buffer_id.to_proto(),
2079 })
2080 .log_err();
2081 }
2082 }
2083 }
2084 }
2085
2086 fn on_lsp_store_event(
2087 &mut self,
2088 _: Model<LspStore>,
2089 event: &LspStoreEvent,
2090 cx: &mut ModelContext<Self>,
2091 ) {
2092 match event {
2093 LspStoreEvent::DiagnosticsUpdated {
2094 language_server_id,
2095 path,
2096 } => cx.emit(Event::DiagnosticsUpdated {
2097 path: path.clone(),
2098 language_server_id: *language_server_id,
2099 }),
2100 LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2101 Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2102 ),
2103 LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2104 cx.emit(Event::LanguageServerRemoved(*language_server_id))
2105 }
2106 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2107 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2108 ),
2109 LspStoreEvent::LanguageDetected {
2110 buffer,
2111 new_language,
2112 } => {
2113 let Some(_) = new_language else {
2114 cx.emit(Event::LanguageNotFound(buffer.clone()));
2115 return;
2116 };
2117 }
2118 LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2119 LspStoreEvent::LanguageServerPrompt(prompt) => {
2120 cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2121 }
2122 LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2123 cx.emit(Event::DiskBasedDiagnosticsStarted {
2124 language_server_id: *language_server_id,
2125 });
2126 }
2127 LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2128 cx.emit(Event::DiskBasedDiagnosticsFinished {
2129 language_server_id: *language_server_id,
2130 });
2131 }
2132 LspStoreEvent::LanguageServerUpdate {
2133 language_server_id,
2134 message,
2135 } => {
2136 if self.is_local() {
2137 self.enqueue_buffer_ordered_message(
2138 BufferOrderedMessage::LanguageServerUpdate {
2139 language_server_id: *language_server_id,
2140 message: message.clone(),
2141 },
2142 )
2143 .ok();
2144 }
2145 }
2146 LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2147 notification_id: "lsp".into(),
2148 message: message.clone(),
2149 }),
2150 LspStoreEvent::SnippetEdit {
2151 buffer_id,
2152 edits,
2153 most_recent_edit,
2154 } => {
2155 if most_recent_edit.replica_id == self.replica_id() {
2156 cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2157 }
2158 }
2159 }
2160 }
2161
2162 fn on_ssh_event(
2163 &mut self,
2164 _: Model<SshRemoteClient>,
2165 event: &remote::SshRemoteEvent,
2166 cx: &mut ModelContext<Self>,
2167 ) {
2168 match event {
2169 remote::SshRemoteEvent::Disconnected => {
2170 // if self.is_via_ssh() {
2171 // self.collaborators.clear();
2172 self.worktree_store.update(cx, |store, cx| {
2173 store.disconnected_from_host(cx);
2174 });
2175 self.buffer_store.update(cx, |buffer_store, cx| {
2176 buffer_store.disconnected_from_host(cx)
2177 });
2178 self.lsp_store.update(cx, |lsp_store, _cx| {
2179 lsp_store.disconnected_from_ssh_remote()
2180 });
2181 cx.emit(Event::DisconnectedFromSshRemote);
2182 }
2183 }
2184 }
2185
2186 fn on_settings_observer_event(
2187 &mut self,
2188 _: Model<SettingsObserver>,
2189 event: &SettingsObserverEvent,
2190 cx: &mut ModelContext<Self>,
2191 ) {
2192 match event {
2193 SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2194 Err(InvalidSettingsError::LocalSettings { message, path }) => {
2195 let message =
2196 format!("Failed to set local settings in {:?}:\n{}", path, message);
2197 cx.emit(Event::Toast {
2198 notification_id: "local-settings".into(),
2199 message,
2200 });
2201 }
2202 Ok(_) => cx.emit(Event::HideToast {
2203 notification_id: "local-settings".into(),
2204 }),
2205 Err(_) => {}
2206 },
2207 }
2208 }
2209
2210 fn on_worktree_store_event(
2211 &mut self,
2212 _: Model<WorktreeStore>,
2213 event: &WorktreeStoreEvent,
2214 cx: &mut ModelContext<Self>,
2215 ) {
2216 match event {
2217 WorktreeStoreEvent::WorktreeAdded(worktree) => {
2218 self.on_worktree_added(worktree, cx);
2219 cx.emit(Event::WorktreeAdded);
2220 }
2221 WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2222 self.on_worktree_removed(*id, cx);
2223 cx.emit(Event::WorktreeRemoved(*id));
2224 }
2225 WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2226 WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2227 }
2228 }
2229
2230 fn on_worktree_added(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
2231 {
2232 let mut remotely_created_models = self.remotely_created_models.lock();
2233 if remotely_created_models.retain_count > 0 {
2234 remotely_created_models.worktrees.push(worktree.clone())
2235 }
2236 }
2237 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
2238 cx.subscribe(worktree, |project, worktree, event, cx| match event {
2239 worktree::Event::UpdatedEntries(changes) => {
2240 cx.emit(Event::WorktreeUpdatedEntries(
2241 worktree.read(cx).id(),
2242 changes.clone(),
2243 ));
2244
2245 let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
2246 project
2247 .client()
2248 .telemetry()
2249 .report_discovered_project_events(worktree_id, changes);
2250 }
2251 worktree::Event::UpdatedGitRepositories(_) => {
2252 cx.emit(Event::WorktreeUpdatedGitRepositories);
2253 }
2254 worktree::Event::DeletedEntry(id) => cx.emit(Event::DeletedEntry(*id)),
2255 })
2256 .detach();
2257 cx.notify();
2258 }
2259
2260 fn on_worktree_removed(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
2261 if let Some(dev_server_project_id) = self.dev_server_project_id {
2262 let paths: Vec<String> = self
2263 .visible_worktrees(cx)
2264 .filter_map(|worktree| {
2265 if worktree.read(cx).id() == id_to_remove {
2266 None
2267 } else {
2268 Some(worktree.read(cx).abs_path().to_string_lossy().to_string())
2269 }
2270 })
2271 .collect();
2272 if !paths.is_empty() {
2273 let request = self.client.request(proto::UpdateDevServerProject {
2274 dev_server_project_id: dev_server_project_id.0,
2275 paths,
2276 });
2277 cx.background_executor()
2278 .spawn(request)
2279 .detach_and_log_err(cx);
2280 }
2281 return;
2282 }
2283
2284 if let Some(ssh) = &self.ssh_client {
2285 ssh.read(cx)
2286 .proto_client()
2287 .send(proto::RemoveWorktree {
2288 worktree_id: id_to_remove.to_proto(),
2289 })
2290 .log_err();
2291 }
2292
2293 cx.notify();
2294 }
2295
2296 fn on_buffer_event(
2297 &mut self,
2298 buffer: Model<Buffer>,
2299 event: &BufferEvent,
2300 cx: &mut ModelContext<Self>,
2301 ) -> Option<()> {
2302 if matches!(
2303 event,
2304 BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
2305 ) {
2306 self.request_buffer_diff_recalculation(&buffer, cx);
2307 }
2308
2309 let buffer_id = buffer.read(cx).remote_id();
2310 match event {
2311 BufferEvent::Operation {
2312 operation,
2313 is_local: true,
2314 } => {
2315 let operation = language::proto::serialize_operation(operation);
2316
2317 if let Some(ssh) = &self.ssh_client {
2318 ssh.read(cx)
2319 .proto_client()
2320 .send(proto::UpdateBuffer {
2321 project_id: 0,
2322 buffer_id: buffer_id.to_proto(),
2323 operations: vec![operation.clone()],
2324 })
2325 .ok();
2326 }
2327
2328 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2329 buffer_id,
2330 operation,
2331 })
2332 .ok();
2333 }
2334
2335 _ => {}
2336 }
2337
2338 None
2339 }
2340
2341 fn request_buffer_diff_recalculation(
2342 &mut self,
2343 buffer: &Model<Buffer>,
2344 cx: &mut ModelContext<Self>,
2345 ) {
2346 self.buffers_needing_diff.insert(buffer.downgrade());
2347 let first_insertion = self.buffers_needing_diff.len() == 1;
2348
2349 let settings = ProjectSettings::get_global(cx);
2350 let delay = if let Some(delay) = settings.git.gutter_debounce {
2351 delay
2352 } else {
2353 if first_insertion {
2354 let this = cx.weak_model();
2355 cx.defer(move |cx| {
2356 if let Some(this) = this.upgrade() {
2357 this.update(cx, |this, cx| {
2358 this.recalculate_buffer_diffs(cx).detach();
2359 });
2360 }
2361 });
2362 }
2363 return;
2364 };
2365
2366 const MIN_DELAY: u64 = 50;
2367 let delay = delay.max(MIN_DELAY);
2368 let duration = Duration::from_millis(delay);
2369
2370 self.git_diff_debouncer
2371 .fire_new(duration, cx, move |this, cx| {
2372 this.recalculate_buffer_diffs(cx)
2373 });
2374 }
2375
2376 fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2377 let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
2378 cx.spawn(move |this, mut cx| async move {
2379 let tasks: Vec<_> = buffers
2380 .iter()
2381 .filter_map(|buffer| {
2382 let buffer = buffer.upgrade()?;
2383 buffer
2384 .update(&mut cx, |buffer, cx| buffer.recalculate_diff(cx))
2385 .ok()
2386 .flatten()
2387 })
2388 .collect();
2389
2390 futures::future::join_all(tasks).await;
2391
2392 this.update(&mut cx, |this, cx| {
2393 if this.buffers_needing_diff.is_empty() {
2394 // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2395 for buffer in buffers {
2396 if let Some(buffer) = buffer.upgrade() {
2397 buffer.update(cx, |_, cx| cx.notify());
2398 }
2399 }
2400 } else {
2401 this.recalculate_buffer_diffs(cx).detach();
2402 }
2403 })
2404 .ok();
2405 })
2406 }
2407
2408 pub fn set_language_for_buffer(
2409 &mut self,
2410 buffer: &Model<Buffer>,
2411 new_language: Arc<Language>,
2412 cx: &mut ModelContext<Self>,
2413 ) {
2414 self.lsp_store.update(cx, |lsp_store, cx| {
2415 lsp_store.set_language_for_buffer(buffer, new_language, cx)
2416 })
2417 }
2418
2419 pub fn restart_language_servers_for_buffers(
2420 &mut self,
2421 buffers: impl IntoIterator<Item = Model<Buffer>>,
2422 cx: &mut ModelContext<Self>,
2423 ) {
2424 self.lsp_store.update(cx, |lsp_store, cx| {
2425 lsp_store.restart_language_servers_for_buffers(buffers, cx)
2426 })
2427 }
2428
2429 pub fn cancel_language_server_work_for_buffers(
2430 &mut self,
2431 buffers: impl IntoIterator<Item = Model<Buffer>>,
2432 cx: &mut ModelContext<Self>,
2433 ) {
2434 self.lsp_store.update(cx, |lsp_store, cx| {
2435 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2436 })
2437 }
2438
2439 pub fn cancel_language_server_work(
2440 &mut self,
2441 server_id: LanguageServerId,
2442 token_to_cancel: Option<String>,
2443 cx: &mut ModelContext<Self>,
2444 ) {
2445 self.lsp_store.update(cx, |lsp_store, cx| {
2446 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2447 })
2448 }
2449
2450 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
2451 self.buffer_ordered_messages_tx
2452 .unbounded_send(message)
2453 .map_err(|e| anyhow!(e))
2454 }
2455
2456 pub fn language_server_statuses<'a>(
2457 &'a self,
2458 cx: &'a AppContext,
2459 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
2460 self.lsp_store.read(cx).language_server_statuses()
2461 }
2462
2463 pub fn last_formatting_failure<'a>(&self, cx: &'a AppContext) -> Option<&'a str> {
2464 self.lsp_store.read(cx).last_formatting_failure()
2465 }
2466
2467 pub fn update_diagnostics(
2468 &mut self,
2469 language_server_id: LanguageServerId,
2470 params: lsp::PublishDiagnosticsParams,
2471 disk_based_sources: &[String],
2472 cx: &mut ModelContext<Self>,
2473 ) -> Result<()> {
2474 self.lsp_store.update(cx, |lsp_store, cx| {
2475 lsp_store.update_diagnostics(language_server_id, params, disk_based_sources, cx)
2476 })
2477 }
2478
2479 pub fn update_diagnostic_entries(
2480 &mut self,
2481 server_id: LanguageServerId,
2482 abs_path: PathBuf,
2483 version: Option<i32>,
2484 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2485 cx: &mut ModelContext<Project>,
2486 ) -> Result<(), anyhow::Error> {
2487 self.lsp_store.update(cx, |lsp_store, cx| {
2488 lsp_store.update_diagnostic_entries(server_id, abs_path, version, diagnostics, cx)
2489 })
2490 }
2491
2492 pub fn reload_buffers(
2493 &self,
2494 buffers: HashSet<Model<Buffer>>,
2495 push_to_history: bool,
2496 cx: &mut ModelContext<Self>,
2497 ) -> Task<Result<ProjectTransaction>> {
2498 self.buffer_store.update(cx, |buffer_store, cx| {
2499 buffer_store.reload_buffers(buffers, push_to_history, cx)
2500 })
2501 }
2502
2503 pub fn format(
2504 &mut self,
2505 buffers: HashSet<Model<Buffer>>,
2506 push_to_history: bool,
2507 trigger: lsp_store::FormatTrigger,
2508 target: lsp_store::FormatTarget,
2509 cx: &mut ModelContext<Project>,
2510 ) -> Task<anyhow::Result<ProjectTransaction>> {
2511 self.lsp_store.update(cx, |lsp_store, cx| {
2512 lsp_store.format(buffers, push_to_history, trigger, target, cx)
2513 })
2514 }
2515
2516 #[inline(never)]
2517 fn definition_impl(
2518 &mut self,
2519 buffer: &Model<Buffer>,
2520 position: PointUtf16,
2521 cx: &mut ModelContext<Self>,
2522 ) -> Task<Result<Vec<LocationLink>>> {
2523 self.request_lsp(
2524 buffer.clone(),
2525 LanguageServerToQuery::Primary,
2526 GetDefinition { position },
2527 cx,
2528 )
2529 }
2530 pub fn definition<T: ToPointUtf16>(
2531 &mut self,
2532 buffer: &Model<Buffer>,
2533 position: T,
2534 cx: &mut ModelContext<Self>,
2535 ) -> Task<Result<Vec<LocationLink>>> {
2536 let position = position.to_point_utf16(buffer.read(cx));
2537 self.definition_impl(buffer, position, cx)
2538 }
2539
2540 fn declaration_impl(
2541 &mut self,
2542 buffer: &Model<Buffer>,
2543 position: PointUtf16,
2544 cx: &mut ModelContext<Self>,
2545 ) -> Task<Result<Vec<LocationLink>>> {
2546 self.request_lsp(
2547 buffer.clone(),
2548 LanguageServerToQuery::Primary,
2549 GetDeclaration { position },
2550 cx,
2551 )
2552 }
2553
2554 pub fn declaration<T: ToPointUtf16>(
2555 &mut self,
2556 buffer: &Model<Buffer>,
2557 position: T,
2558 cx: &mut ModelContext<Self>,
2559 ) -> Task<Result<Vec<LocationLink>>> {
2560 let position = position.to_point_utf16(buffer.read(cx));
2561 self.declaration_impl(buffer, position, cx)
2562 }
2563
2564 fn type_definition_impl(
2565 &mut self,
2566 buffer: &Model<Buffer>,
2567 position: PointUtf16,
2568 cx: &mut ModelContext<Self>,
2569 ) -> Task<Result<Vec<LocationLink>>> {
2570 self.request_lsp(
2571 buffer.clone(),
2572 LanguageServerToQuery::Primary,
2573 GetTypeDefinition { position },
2574 cx,
2575 )
2576 }
2577
2578 pub fn type_definition<T: ToPointUtf16>(
2579 &mut self,
2580 buffer: &Model<Buffer>,
2581 position: T,
2582 cx: &mut ModelContext<Self>,
2583 ) -> Task<Result<Vec<LocationLink>>> {
2584 let position = position.to_point_utf16(buffer.read(cx));
2585 self.type_definition_impl(buffer, position, cx)
2586 }
2587
2588 pub fn implementation<T: ToPointUtf16>(
2589 &mut self,
2590 buffer: &Model<Buffer>,
2591 position: T,
2592 cx: &mut ModelContext<Self>,
2593 ) -> Task<Result<Vec<LocationLink>>> {
2594 let position = position.to_point_utf16(buffer.read(cx));
2595 self.request_lsp(
2596 buffer.clone(),
2597 LanguageServerToQuery::Primary,
2598 GetImplementation { position },
2599 cx,
2600 )
2601 }
2602
2603 pub fn references<T: ToPointUtf16>(
2604 &mut self,
2605 buffer: &Model<Buffer>,
2606 position: T,
2607 cx: &mut ModelContext<Self>,
2608 ) -> Task<Result<Vec<Location>>> {
2609 let position = position.to_point_utf16(buffer.read(cx));
2610 self.request_lsp(
2611 buffer.clone(),
2612 LanguageServerToQuery::Primary,
2613 GetReferences { position },
2614 cx,
2615 )
2616 }
2617
2618 fn document_highlights_impl(
2619 &mut self,
2620 buffer: &Model<Buffer>,
2621 position: PointUtf16,
2622 cx: &mut ModelContext<Self>,
2623 ) -> Task<Result<Vec<DocumentHighlight>>> {
2624 self.request_lsp(
2625 buffer.clone(),
2626 LanguageServerToQuery::Primary,
2627 GetDocumentHighlights { position },
2628 cx,
2629 )
2630 }
2631
2632 pub fn document_highlights<T: ToPointUtf16>(
2633 &mut self,
2634 buffer: &Model<Buffer>,
2635 position: T,
2636 cx: &mut ModelContext<Self>,
2637 ) -> Task<Result<Vec<DocumentHighlight>>> {
2638 let position = position.to_point_utf16(buffer.read(cx));
2639 self.document_highlights_impl(buffer, position, cx)
2640 }
2641
2642 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
2643 self.lsp_store
2644 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
2645 }
2646
2647 pub fn open_buffer_for_symbol(
2648 &mut self,
2649 symbol: &Symbol,
2650 cx: &mut ModelContext<Self>,
2651 ) -> Task<Result<Model<Buffer>>> {
2652 self.lsp_store.update(cx, |lsp_store, cx| {
2653 lsp_store.open_buffer_for_symbol(symbol, cx)
2654 })
2655 }
2656
2657 pub fn open_server_settings(
2658 &mut self,
2659 cx: &mut ModelContext<Self>,
2660 ) -> Task<Result<Model<Buffer>>> {
2661 let guard = self.retain_remotely_created_models(cx);
2662 let Some(ssh_client) = self.ssh_client.as_ref() else {
2663 return Task::ready(Err(anyhow!("not an ssh project")));
2664 };
2665
2666 let proto_client = ssh_client.read(cx).proto_client();
2667
2668 cx.spawn(|this, mut cx| async move {
2669 let buffer = proto_client
2670 .request(proto::OpenServerSettings {
2671 project_id: SSH_PROJECT_ID,
2672 })
2673 .await?;
2674
2675 let buffer = this
2676 .update(&mut cx, |this, cx| {
2677 anyhow::Ok(this.wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx))
2678 })??
2679 .await;
2680
2681 drop(guard);
2682 buffer
2683 })
2684 }
2685
2686 pub fn open_local_buffer_via_lsp(
2687 &mut self,
2688 abs_path: lsp::Url,
2689 language_server_id: LanguageServerId,
2690 language_server_name: LanguageServerName,
2691 cx: &mut ModelContext<Self>,
2692 ) -> Task<Result<Model<Buffer>>> {
2693 self.lsp_store.update(cx, |lsp_store, cx| {
2694 lsp_store.open_local_buffer_via_lsp(
2695 abs_path,
2696 language_server_id,
2697 language_server_name,
2698 cx,
2699 )
2700 })
2701 }
2702
2703 pub fn signature_help<T: ToPointUtf16>(
2704 &self,
2705 buffer: &Model<Buffer>,
2706 position: T,
2707 cx: &mut ModelContext<Self>,
2708 ) -> Task<Vec<SignatureHelp>> {
2709 self.lsp_store.update(cx, |lsp_store, cx| {
2710 lsp_store.signature_help(buffer, position, cx)
2711 })
2712 }
2713
2714 pub fn hover<T: ToPointUtf16>(
2715 &self,
2716 buffer: &Model<Buffer>,
2717 position: T,
2718 cx: &mut ModelContext<Self>,
2719 ) -> Task<Vec<Hover>> {
2720 let position = position.to_point_utf16(buffer.read(cx));
2721 self.lsp_store
2722 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
2723 }
2724
2725 pub fn linked_edit(
2726 &self,
2727 buffer: &Model<Buffer>,
2728 position: Anchor,
2729 cx: &mut ModelContext<Self>,
2730 ) -> Task<Result<Vec<Range<Anchor>>>> {
2731 self.lsp_store.update(cx, |lsp_store, cx| {
2732 lsp_store.linked_edit(buffer, position, cx)
2733 })
2734 }
2735
2736 pub fn completions<T: ToOffset + ToPointUtf16>(
2737 &self,
2738 buffer: &Model<Buffer>,
2739 position: T,
2740 context: CompletionContext,
2741 cx: &mut ModelContext<Self>,
2742 ) -> Task<Result<Vec<Completion>>> {
2743 let position = position.to_point_utf16(buffer.read(cx));
2744 self.lsp_store.update(cx, |lsp_store, cx| {
2745 lsp_store.completions(buffer, position, context, cx)
2746 })
2747 }
2748
2749 pub fn resolve_completions(
2750 &self,
2751 buffer: Model<Buffer>,
2752 completion_indices: Vec<usize>,
2753 completions: Arc<RwLock<Box<[Completion]>>>,
2754 cx: &mut ModelContext<Self>,
2755 ) -> Task<Result<bool>> {
2756 self.lsp_store.update(cx, |lsp_store, cx| {
2757 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
2758 })
2759 }
2760
2761 pub fn apply_additional_edits_for_completion(
2762 &self,
2763 buffer_handle: Model<Buffer>,
2764 completion: Completion,
2765 push_to_history: bool,
2766 cx: &mut ModelContext<Self>,
2767 ) -> Task<Result<Option<Transaction>>> {
2768 self.lsp_store.update(cx, |lsp_store, cx| {
2769 lsp_store.apply_additional_edits_for_completion(
2770 buffer_handle,
2771 completion,
2772 push_to_history,
2773 cx,
2774 )
2775 })
2776 }
2777
2778 pub fn code_actions<T: Clone + ToOffset>(
2779 &mut self,
2780 buffer_handle: &Model<Buffer>,
2781 range: Range<T>,
2782 cx: &mut ModelContext<Self>,
2783 ) -> Task<Result<Vec<CodeAction>>> {
2784 let buffer = buffer_handle.read(cx);
2785 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2786 self.lsp_store.update(cx, |lsp_store, cx| {
2787 lsp_store.code_actions(buffer_handle, range, cx)
2788 })
2789 }
2790
2791 pub fn apply_code_action(
2792 &self,
2793 buffer_handle: Model<Buffer>,
2794 action: CodeAction,
2795 push_to_history: bool,
2796 cx: &mut ModelContext<Self>,
2797 ) -> Task<Result<ProjectTransaction>> {
2798 self.lsp_store.update(cx, |lsp_store, cx| {
2799 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
2800 })
2801 }
2802
2803 fn prepare_rename_impl(
2804 &mut self,
2805 buffer: Model<Buffer>,
2806 position: PointUtf16,
2807 cx: &mut ModelContext<Self>,
2808 ) -> Task<Result<Option<Range<Anchor>>>> {
2809 self.request_lsp(
2810 buffer,
2811 LanguageServerToQuery::Primary,
2812 PrepareRename { position },
2813 cx,
2814 )
2815 }
2816 pub fn prepare_rename<T: ToPointUtf16>(
2817 &mut self,
2818 buffer: Model<Buffer>,
2819 position: T,
2820 cx: &mut ModelContext<Self>,
2821 ) -> Task<Result<Option<Range<Anchor>>>> {
2822 let position = position.to_point_utf16(buffer.read(cx));
2823 self.prepare_rename_impl(buffer, position, cx)
2824 }
2825
2826 fn perform_rename_impl(
2827 &mut self,
2828 buffer: Model<Buffer>,
2829 position: PointUtf16,
2830 new_name: String,
2831 push_to_history: bool,
2832 cx: &mut ModelContext<Self>,
2833 ) -> Task<Result<ProjectTransaction>> {
2834 let position = position.to_point_utf16(buffer.read(cx));
2835 self.request_lsp(
2836 buffer,
2837 LanguageServerToQuery::Primary,
2838 PerformRename {
2839 position,
2840 new_name,
2841 push_to_history,
2842 },
2843 cx,
2844 )
2845 }
2846
2847 pub fn perform_rename<T: ToPointUtf16>(
2848 &mut self,
2849 buffer: Model<Buffer>,
2850 position: T,
2851 new_name: String,
2852 cx: &mut ModelContext<Self>,
2853 ) -> Task<Result<ProjectTransaction>> {
2854 let position = position.to_point_utf16(buffer.read(cx));
2855 self.perform_rename_impl(buffer, position, new_name, true, cx)
2856 }
2857
2858 pub fn on_type_format<T: ToPointUtf16>(
2859 &mut self,
2860 buffer: Model<Buffer>,
2861 position: T,
2862 trigger: String,
2863 push_to_history: bool,
2864 cx: &mut ModelContext<Self>,
2865 ) -> Task<Result<Option<Transaction>>> {
2866 self.lsp_store.update(cx, |lsp_store, cx| {
2867 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
2868 })
2869 }
2870
2871 pub fn inlay_hints<T: ToOffset>(
2872 &mut self,
2873 buffer_handle: Model<Buffer>,
2874 range: Range<T>,
2875 cx: &mut ModelContext<Self>,
2876 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
2877 let buffer = buffer_handle.read(cx);
2878 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2879 self.lsp_store.update(cx, |lsp_store, cx| {
2880 lsp_store.inlay_hints(buffer_handle, range, cx)
2881 })
2882 }
2883
2884 pub fn resolve_inlay_hint(
2885 &self,
2886 hint: InlayHint,
2887 buffer_handle: Model<Buffer>,
2888 server_id: LanguageServerId,
2889 cx: &mut ModelContext<Self>,
2890 ) -> Task<anyhow::Result<InlayHint>> {
2891 self.lsp_store.update(cx, |lsp_store, cx| {
2892 lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
2893 })
2894 }
2895
2896 pub fn search(
2897 &mut self,
2898 query: SearchQuery,
2899 cx: &mut ModelContext<Self>,
2900 ) -> Receiver<SearchResult> {
2901 let (result_tx, result_rx) = smol::channel::unbounded();
2902
2903 let matching_buffers_rx = if query.is_opened_only() {
2904 self.sort_search_candidates(&query, cx)
2905 } else {
2906 self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
2907 };
2908
2909 cx.spawn(|_, cx| async move {
2910 let mut range_count = 0;
2911 let mut buffer_count = 0;
2912 let mut limit_reached = false;
2913 let query = Arc::new(query);
2914 let mut chunks = matching_buffers_rx.ready_chunks(64);
2915
2916 // Now that we know what paths match the query, we will load at most
2917 // 64 buffers at a time to avoid overwhelming the main thread. For each
2918 // opened buffer, we will spawn a background task that retrieves all the
2919 // ranges in the buffer matched by the query.
2920 'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
2921 let mut chunk_results = Vec::new();
2922 for buffer in matching_buffer_chunk {
2923 let buffer = buffer.clone();
2924 let query = query.clone();
2925 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
2926 chunk_results.push(cx.background_executor().spawn(async move {
2927 let ranges = query
2928 .search(&snapshot, None)
2929 .await
2930 .iter()
2931 .map(|range| {
2932 snapshot.anchor_before(range.start)
2933 ..snapshot.anchor_after(range.end)
2934 })
2935 .collect::<Vec<_>>();
2936 anyhow::Ok((buffer, ranges))
2937 }));
2938 }
2939
2940 let chunk_results = futures::future::join_all(chunk_results).await;
2941 for result in chunk_results {
2942 if let Some((buffer, ranges)) = result.log_err() {
2943 range_count += ranges.len();
2944 buffer_count += 1;
2945 result_tx
2946 .send(SearchResult::Buffer { buffer, ranges })
2947 .await?;
2948 if buffer_count > MAX_SEARCH_RESULT_FILES
2949 || range_count > MAX_SEARCH_RESULT_RANGES
2950 {
2951 limit_reached = true;
2952 break 'outer;
2953 }
2954 }
2955 }
2956 }
2957
2958 if limit_reached {
2959 result_tx.send(SearchResult::LimitReached).await?;
2960 }
2961
2962 anyhow::Ok(())
2963 })
2964 .detach();
2965
2966 result_rx
2967 }
2968
2969 fn find_search_candidate_buffers(
2970 &mut self,
2971 query: &SearchQuery,
2972 limit: usize,
2973 cx: &mut ModelContext<Project>,
2974 ) -> Receiver<Model<Buffer>> {
2975 if self.is_local() {
2976 let fs = self.fs.clone();
2977 self.buffer_store.update(cx, |buffer_store, cx| {
2978 buffer_store.find_search_candidates(query, limit, fs, cx)
2979 })
2980 } else {
2981 self.find_search_candidates_remote(query, limit, cx)
2982 }
2983 }
2984
2985 fn sort_search_candidates(
2986 &mut self,
2987 search_query: &SearchQuery,
2988 cx: &mut ModelContext<Project>,
2989 ) -> Receiver<Model<Buffer>> {
2990 let worktree_store = self.worktree_store.read(cx);
2991 let mut buffers = search_query
2992 .buffers()
2993 .into_iter()
2994 .flatten()
2995 .filter(|buffer| {
2996 let b = buffer.read(cx);
2997 if let Some(file) = b.file() {
2998 if !search_query.file_matches(file.path()) {
2999 return false;
3000 }
3001 if let Some(entry) = b
3002 .entry_id(cx)
3003 .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3004 {
3005 if entry.is_ignored && !search_query.include_ignored() {
3006 return false;
3007 }
3008 }
3009 }
3010 true
3011 })
3012 .collect::<Vec<_>>();
3013 let (tx, rx) = smol::channel::unbounded();
3014 buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3015 (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3016 (None, Some(_)) => std::cmp::Ordering::Less,
3017 (Some(_), None) => std::cmp::Ordering::Greater,
3018 (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3019 });
3020 for buffer in buffers {
3021 tx.send_blocking(buffer.clone()).unwrap()
3022 }
3023
3024 rx
3025 }
3026
3027 fn find_search_candidates_remote(
3028 &mut self,
3029 query: &SearchQuery,
3030 limit: usize,
3031 cx: &mut ModelContext<Project>,
3032 ) -> Receiver<Model<Buffer>> {
3033 let (tx, rx) = smol::channel::unbounded();
3034
3035 let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3036 (ssh_client.read(cx).proto_client(), 0)
3037 } else if let Some(remote_id) = self.remote_id() {
3038 (self.client.clone().into(), remote_id)
3039 } else {
3040 return rx;
3041 };
3042
3043 let request = client.request(proto::FindSearchCandidates {
3044 project_id: remote_id,
3045 query: Some(query.to_proto()),
3046 limit: limit as _,
3047 });
3048 let guard = self.retain_remotely_created_models(cx);
3049
3050 cx.spawn(move |this, mut cx| async move {
3051 let response = request.await?;
3052 for buffer_id in response.buffer_ids {
3053 let buffer_id = BufferId::new(buffer_id)?;
3054 let buffer = this
3055 .update(&mut cx, |this, cx| {
3056 this.wait_for_remote_buffer(buffer_id, cx)
3057 })?
3058 .await?;
3059 let _ = tx.send(buffer).await;
3060 }
3061
3062 drop(guard);
3063 anyhow::Ok(())
3064 })
3065 .detach_and_log_err(cx);
3066 rx
3067 }
3068
3069 pub fn request_lsp<R: LspCommand>(
3070 &mut self,
3071 buffer_handle: Model<Buffer>,
3072 server: LanguageServerToQuery,
3073 request: R,
3074 cx: &mut ModelContext<Self>,
3075 ) -> Task<Result<R::Response>>
3076 where
3077 <R::LspRequest as lsp::request::Request>::Result: Send,
3078 <R::LspRequest as lsp::request::Request>::Params: Send,
3079 {
3080 let guard = self.retain_remotely_created_models(cx);
3081 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3082 lsp_store.request_lsp(buffer_handle, server, request, cx)
3083 });
3084 cx.spawn(|_, _| async move {
3085 let result = task.await;
3086 drop(guard);
3087 result
3088 })
3089 }
3090
3091 /// Move a worktree to a new position in the worktree order.
3092 ///
3093 /// The worktree will moved to the opposite side of the destination worktree.
3094 ///
3095 /// # Example
3096 ///
3097 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3098 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3099 ///
3100 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3101 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3102 ///
3103 /// # Errors
3104 ///
3105 /// An error will be returned if the worktree or destination worktree are not found.
3106 pub fn move_worktree(
3107 &mut self,
3108 source: WorktreeId,
3109 destination: WorktreeId,
3110 cx: &mut ModelContext<'_, Self>,
3111 ) -> Result<()> {
3112 self.worktree_store.update(cx, |worktree_store, cx| {
3113 worktree_store.move_worktree(source, destination, cx)
3114 })
3115 }
3116
3117 pub fn find_or_create_worktree(
3118 &mut self,
3119 abs_path: impl AsRef<Path>,
3120 visible: bool,
3121 cx: &mut ModelContext<Self>,
3122 ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
3123 self.worktree_store.update(cx, |worktree_store, cx| {
3124 worktree_store.find_or_create_worktree(abs_path, visible, cx)
3125 })
3126 }
3127
3128 pub fn find_worktree(
3129 &self,
3130 abs_path: &Path,
3131 cx: &AppContext,
3132 ) -> Option<(Model<Worktree>, PathBuf)> {
3133 self.worktree_store.read_with(cx, |worktree_store, cx| {
3134 worktree_store.find_worktree(abs_path, cx)
3135 })
3136 }
3137
3138 pub fn is_shared(&self) -> bool {
3139 match &self.client_state {
3140 ProjectClientState::Shared { .. } => true,
3141 ProjectClientState::Local => false,
3142 ProjectClientState::Remote { in_room, .. } => *in_room,
3143 }
3144 }
3145
3146 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3147 pub fn resolve_existing_file_path(
3148 &self,
3149 path: &str,
3150 buffer: &Model<Buffer>,
3151 cx: &mut ModelContext<Self>,
3152 ) -> Task<Option<ResolvedPath>> {
3153 let path_buf = PathBuf::from(path);
3154 if path_buf.is_absolute() || path.starts_with("~") {
3155 self.resolve_abs_file_path(path, cx)
3156 } else {
3157 self.resolve_path_in_worktrees(path_buf, buffer, cx)
3158 }
3159 }
3160
3161 pub fn abs_file_path_exists(&self, path: &str, cx: &mut ModelContext<Self>) -> Task<bool> {
3162 let resolve_task = self.resolve_abs_file_path(path, cx);
3163 cx.background_executor().spawn(async move {
3164 let resolved_path = resolve_task.await;
3165 resolved_path.is_some()
3166 })
3167 }
3168
3169 fn resolve_abs_file_path(
3170 &self,
3171 path: &str,
3172 cx: &mut ModelContext<Self>,
3173 ) -> Task<Option<ResolvedPath>> {
3174 if self.is_local() {
3175 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3176
3177 let fs = self.fs.clone();
3178 cx.background_executor().spawn(async move {
3179 let path = expanded.as_path();
3180 let exists = fs.is_file(path).await;
3181
3182 exists.then(|| ResolvedPath::AbsPath(expanded))
3183 })
3184 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3185 let request = ssh_client
3186 .read(cx)
3187 .proto_client()
3188 .request(proto::CheckFileExists {
3189 project_id: SSH_PROJECT_ID,
3190 path: path.to_string(),
3191 });
3192 cx.background_executor().spawn(async move {
3193 let response = request.await.log_err()?;
3194 if response.exists {
3195 Some(ResolvedPath::AbsPath(PathBuf::from(response.path)))
3196 } else {
3197 None
3198 }
3199 })
3200 } else {
3201 return Task::ready(None);
3202 }
3203 }
3204
3205 fn resolve_path_in_worktrees(
3206 &self,
3207 path: PathBuf,
3208 buffer: &Model<Buffer>,
3209 cx: &mut ModelContext<Self>,
3210 ) -> Task<Option<ResolvedPath>> {
3211 let mut candidates = vec![path.clone()];
3212
3213 if let Some(file) = buffer.read(cx).file() {
3214 if let Some(dir) = file.path().parent() {
3215 let joined = dir.to_path_buf().join(path);
3216 candidates.push(joined);
3217 }
3218 }
3219
3220 let worktrees = self.worktrees(cx).collect::<Vec<_>>();
3221 cx.spawn(|_, mut cx| async move {
3222 for worktree in worktrees {
3223 for candidate in candidates.iter() {
3224 let path = worktree
3225 .update(&mut cx, |worktree, _| {
3226 let root_entry_path = &worktree.root_entry()?.path;
3227
3228 let resolved = resolve_path(root_entry_path, candidate);
3229
3230 let stripped =
3231 resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3232
3233 worktree.entry_for_path(stripped).map(|entry| {
3234 ResolvedPath::ProjectPath(ProjectPath {
3235 worktree_id: worktree.id(),
3236 path: entry.path.clone(),
3237 })
3238 })
3239 })
3240 .ok()?;
3241
3242 if path.is_some() {
3243 return path;
3244 }
3245 }
3246 }
3247 None
3248 })
3249 }
3250
3251 pub fn list_directory(
3252 &self,
3253 query: String,
3254 cx: &mut ModelContext<Self>,
3255 ) -> Task<Result<Vec<PathBuf>>> {
3256 if self.is_local() {
3257 DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3258 } else if let Some(session) = self.ssh_client.as_ref() {
3259 let request = proto::ListRemoteDirectory {
3260 dev_server_id: SSH_PROJECT_ID,
3261 path: query,
3262 };
3263
3264 let response = session.read(cx).proto_client().request(request);
3265 cx.background_executor().spawn(async move {
3266 let response = response.await?;
3267 Ok(response.entries.into_iter().map(PathBuf::from).collect())
3268 })
3269 } else if let Some(dev_server) = self.dev_server_project_id().and_then(|id| {
3270 dev_server_projects::Store::global(cx)
3271 .read(cx)
3272 .dev_server_for_project(id)
3273 }) {
3274 let request = proto::ListRemoteDirectory {
3275 dev_server_id: dev_server.id.0,
3276 path: query,
3277 };
3278 let response = self.client.request(request);
3279 cx.background_executor().spawn(async move {
3280 let response = response.await?;
3281 Ok(response.entries.into_iter().map(PathBuf::from).collect())
3282 })
3283 } else {
3284 Task::ready(Err(anyhow!("cannot list directory in remote project")))
3285 }
3286 }
3287
3288 pub fn create_worktree(
3289 &mut self,
3290 abs_path: impl AsRef<Path>,
3291 visible: bool,
3292 cx: &mut ModelContext<Self>,
3293 ) -> Task<Result<Model<Worktree>>> {
3294 self.worktree_store.update(cx, |worktree_store, cx| {
3295 worktree_store.create_worktree(abs_path, visible, cx)
3296 })
3297 }
3298
3299 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
3300 self.worktree_store.update(cx, |worktree_store, cx| {
3301 worktree_store.remove_worktree(id_to_remove, cx);
3302 });
3303 }
3304
3305 fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
3306 self.worktree_store.update(cx, |worktree_store, cx| {
3307 worktree_store.add(worktree, cx);
3308 });
3309 }
3310
3311 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
3312 let new_active_entry = entry.and_then(|project_path| {
3313 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3314 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3315 Some(entry.id)
3316 });
3317 if new_active_entry != self.active_entry {
3318 self.active_entry = new_active_entry;
3319 self.lsp_store.update(cx, |lsp_store, _| {
3320 lsp_store.set_active_entry(new_active_entry);
3321 });
3322 cx.emit(Event::ActiveEntryChanged(new_active_entry));
3323 }
3324 }
3325
3326 pub fn language_servers_running_disk_based_diagnostics<'a>(
3327 &'a self,
3328 cx: &'a AppContext,
3329 ) -> impl Iterator<Item = LanguageServerId> + 'a {
3330 self.lsp_store
3331 .read(cx)
3332 .language_servers_running_disk_based_diagnostics()
3333 }
3334
3335 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
3336 let mut summary = DiagnosticSummary::default();
3337 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
3338 summary.error_count += path_summary.error_count;
3339 summary.warning_count += path_summary.warning_count;
3340 }
3341 summary
3342 }
3343
3344 pub fn diagnostic_summaries<'a>(
3345 &'a self,
3346 include_ignored: bool,
3347 cx: &'a AppContext,
3348 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
3349 self.lsp_store
3350 .read(cx)
3351 .diagnostic_summaries(include_ignored, cx)
3352 }
3353
3354 pub fn active_entry(&self) -> Option<ProjectEntryId> {
3355 self.active_entry
3356 }
3357
3358 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
3359 self.worktree_store.read(cx).entry_for_path(path, cx)
3360 }
3361
3362 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
3363 let worktree = self.worktree_for_entry(entry_id, cx)?;
3364 let worktree = worktree.read(cx);
3365 let worktree_id = worktree.id();
3366 let path = worktree.entry_for_id(entry_id)?.path.clone();
3367 Some(ProjectPath { worktree_id, path })
3368 }
3369
3370 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
3371 let workspace_root = self
3372 .worktree_for_id(project_path.worktree_id, cx)?
3373 .read(cx)
3374 .abs_path();
3375 let project_path = project_path.path.as_ref();
3376
3377 Some(if project_path == Path::new("") {
3378 workspace_root.to_path_buf()
3379 } else {
3380 workspace_root.join(project_path)
3381 })
3382 }
3383
3384 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
3385 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
3386 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
3387 /// the first visible worktree that has an entry for that relative path.
3388 ///
3389 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
3390 /// root name from paths.
3391 ///
3392 /// # Arguments
3393 ///
3394 /// * `path` - A full path that starts with a worktree root name, or alternatively a
3395 /// relative path within a visible worktree.
3396 /// * `cx` - A reference to the `AppContext`.
3397 ///
3398 /// # Returns
3399 ///
3400 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
3401 pub fn find_project_path(&self, path: &Path, cx: &AppContext) -> Option<ProjectPath> {
3402 let worktree_store = self.worktree_store.read(cx);
3403
3404 for worktree in worktree_store.visible_worktrees(cx) {
3405 let worktree_root_name = worktree.read(cx).root_name();
3406 if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
3407 return Some(ProjectPath {
3408 worktree_id: worktree.read(cx).id(),
3409 path: relative_path.into(),
3410 });
3411 }
3412 }
3413
3414 for worktree in worktree_store.visible_worktrees(cx) {
3415 let worktree = worktree.read(cx);
3416 if let Some(entry) = worktree.entry_for_path(path) {
3417 return Some(ProjectPath {
3418 worktree_id: worktree.id(),
3419 path: entry.path.clone(),
3420 });
3421 }
3422 }
3423
3424 None
3425 }
3426
3427 pub fn get_workspace_root(
3428 &self,
3429 project_path: &ProjectPath,
3430 cx: &AppContext,
3431 ) -> Option<PathBuf> {
3432 Some(
3433 self.worktree_for_id(project_path.worktree_id, cx)?
3434 .read(cx)
3435 .abs_path()
3436 .to_path_buf(),
3437 )
3438 }
3439
3440 pub fn get_repo(
3441 &self,
3442 project_path: &ProjectPath,
3443 cx: &AppContext,
3444 ) -> Option<Arc<dyn GitRepository>> {
3445 self.worktree_for_id(project_path.worktree_id, cx)?
3446 .read(cx)
3447 .as_local()?
3448 .local_git_repo(&project_path.path)
3449 }
3450
3451 pub fn get_first_worktree_root_repo(&self, cx: &AppContext) -> Option<Arc<dyn GitRepository>> {
3452 let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
3453 let root_entry = worktree.root_git_entry()?;
3454 worktree.get_local_repo(&root_entry)?.repo().clone().into()
3455 }
3456
3457 pub fn blame_buffer(
3458 &self,
3459 buffer: &Model<Buffer>,
3460 version: Option<clock::Global>,
3461 cx: &AppContext,
3462 ) -> Task<Result<Blame>> {
3463 self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
3464 }
3465
3466 // RPC message handlers
3467
3468 async fn handle_unshare_project(
3469 this: Model<Self>,
3470 _: TypedEnvelope<proto::UnshareProject>,
3471 mut cx: AsyncAppContext,
3472 ) -> Result<()> {
3473 this.update(&mut cx, |this, cx| {
3474 if this.is_local() || this.is_via_ssh() {
3475 this.unshare(cx)?;
3476 } else {
3477 this.disconnected_from_host(cx);
3478 }
3479 Ok(())
3480 })?
3481 }
3482
3483 async fn handle_add_collaborator(
3484 this: Model<Self>,
3485 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
3486 mut cx: AsyncAppContext,
3487 ) -> Result<()> {
3488 let collaborator = envelope
3489 .payload
3490 .collaborator
3491 .take()
3492 .ok_or_else(|| anyhow!("empty collaborator"))?;
3493
3494 let collaborator = Collaborator::from_proto(collaborator)?;
3495 this.update(&mut cx, |this, cx| {
3496 this.buffer_store.update(cx, |buffer_store, _| {
3497 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
3498 });
3499 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
3500 this.collaborators
3501 .insert(collaborator.peer_id, collaborator);
3502 cx.notify();
3503 })?;
3504
3505 Ok(())
3506 }
3507
3508 async fn handle_update_project_collaborator(
3509 this: Model<Self>,
3510 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
3511 mut cx: AsyncAppContext,
3512 ) -> Result<()> {
3513 let old_peer_id = envelope
3514 .payload
3515 .old_peer_id
3516 .ok_or_else(|| anyhow!("missing old peer id"))?;
3517 let new_peer_id = envelope
3518 .payload
3519 .new_peer_id
3520 .ok_or_else(|| anyhow!("missing new peer id"))?;
3521 this.update(&mut cx, |this, cx| {
3522 let collaborator = this
3523 .collaborators
3524 .remove(&old_peer_id)
3525 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
3526 let is_host = collaborator.replica_id == 0;
3527 this.collaborators.insert(new_peer_id, collaborator);
3528
3529 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
3530 this.buffer_store.update(cx, |buffer_store, _| {
3531 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
3532 });
3533
3534 if is_host {
3535 this.buffer_store
3536 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
3537 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
3538 .unwrap();
3539 cx.emit(Event::HostReshared);
3540 }
3541
3542 cx.emit(Event::CollaboratorUpdated {
3543 old_peer_id,
3544 new_peer_id,
3545 });
3546 cx.notify();
3547 Ok(())
3548 })?
3549 }
3550
3551 async fn handle_remove_collaborator(
3552 this: Model<Self>,
3553 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
3554 mut cx: AsyncAppContext,
3555 ) -> Result<()> {
3556 this.update(&mut cx, |this, cx| {
3557 let peer_id = envelope
3558 .payload
3559 .peer_id
3560 .ok_or_else(|| anyhow!("invalid peer id"))?;
3561 let replica_id = this
3562 .collaborators
3563 .remove(&peer_id)
3564 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
3565 .replica_id;
3566 this.buffer_store.update(cx, |buffer_store, cx| {
3567 buffer_store.forget_shared_buffers_for(&peer_id);
3568 for buffer in buffer_store.buffers() {
3569 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
3570 }
3571 });
3572
3573 cx.emit(Event::CollaboratorLeft(peer_id));
3574 cx.notify();
3575 Ok(())
3576 })?
3577 }
3578
3579 async fn handle_update_project(
3580 this: Model<Self>,
3581 envelope: TypedEnvelope<proto::UpdateProject>,
3582 mut cx: AsyncAppContext,
3583 ) -> Result<()> {
3584 this.update(&mut cx, |this, cx| {
3585 // Don't handle messages that were sent before the response to us joining the project
3586 if envelope.message_id > this.join_project_response_message_id {
3587 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
3588 }
3589 Ok(())
3590 })?
3591 }
3592
3593 async fn handle_toast(
3594 this: Model<Self>,
3595 envelope: TypedEnvelope<proto::Toast>,
3596 mut cx: AsyncAppContext,
3597 ) -> Result<()> {
3598 this.update(&mut cx, |_, cx| {
3599 cx.emit(Event::Toast {
3600 notification_id: envelope.payload.notification_id.into(),
3601 message: envelope.payload.message,
3602 });
3603 Ok(())
3604 })?
3605 }
3606
3607 async fn handle_hide_toast(
3608 this: Model<Self>,
3609 envelope: TypedEnvelope<proto::HideToast>,
3610 mut cx: AsyncAppContext,
3611 ) -> Result<()> {
3612 this.update(&mut cx, |_, cx| {
3613 cx.emit(Event::HideToast {
3614 notification_id: envelope.payload.notification_id.into(),
3615 });
3616 Ok(())
3617 })?
3618 }
3619
3620 // Collab sends UpdateWorktree protos as messages
3621 async fn handle_update_worktree(
3622 this: Model<Self>,
3623 envelope: TypedEnvelope<proto::UpdateWorktree>,
3624 mut cx: AsyncAppContext,
3625 ) -> Result<()> {
3626 this.update(&mut cx, |this, cx| {
3627 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3628 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
3629 worktree.update(cx, |worktree, _| {
3630 let worktree = worktree.as_remote_mut().unwrap();
3631 worktree.update_from_remote(envelope.payload);
3632 });
3633 }
3634 Ok(())
3635 })?
3636 }
3637
3638 async fn handle_update_buffer(
3639 this: Model<Self>,
3640 envelope: TypedEnvelope<proto::UpdateBuffer>,
3641 cx: AsyncAppContext,
3642 ) -> Result<proto::Ack> {
3643 let buffer_store = this.read_with(&cx, |this, cx| {
3644 if let Some(ssh) = &this.ssh_client {
3645 let mut payload = envelope.payload.clone();
3646 payload.project_id = SSH_PROJECT_ID;
3647 cx.background_executor()
3648 .spawn(ssh.read(cx).proto_client().request(payload))
3649 .detach_and_log_err(cx);
3650 }
3651 this.buffer_store.clone()
3652 })?;
3653 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3654 }
3655
3656 fn retain_remotely_created_models(
3657 &mut self,
3658 cx: &mut ModelContext<Self>,
3659 ) -> RemotelyCreatedModelGuard {
3660 {
3661 let mut remotely_create_models = self.remotely_created_models.lock();
3662 if remotely_create_models.retain_count == 0 {
3663 remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
3664 remotely_create_models.worktrees =
3665 self.worktree_store.read(cx).worktrees().collect();
3666 }
3667 remotely_create_models.retain_count += 1;
3668 }
3669 RemotelyCreatedModelGuard {
3670 remote_models: Arc::downgrade(&self.remotely_created_models),
3671 }
3672 }
3673
3674 async fn handle_create_buffer_for_peer(
3675 this: Model<Self>,
3676 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
3677 mut cx: AsyncAppContext,
3678 ) -> Result<()> {
3679 this.update(&mut cx, |this, cx| {
3680 this.buffer_store.update(cx, |buffer_store, cx| {
3681 buffer_store.handle_create_buffer_for_peer(
3682 envelope,
3683 this.replica_id(),
3684 this.capability(),
3685 cx,
3686 )
3687 })
3688 })?
3689 }
3690
3691 async fn handle_synchronize_buffers(
3692 this: Model<Self>,
3693 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
3694 mut cx: AsyncAppContext,
3695 ) -> Result<proto::SynchronizeBuffersResponse> {
3696 let response = this.update(&mut cx, |this, cx| {
3697 let client = this.client.clone();
3698 this.buffer_store.update(cx, |this, cx| {
3699 this.handle_synchronize_buffers(envelope, cx, client)
3700 })
3701 })??;
3702
3703 Ok(response)
3704 }
3705
3706 async fn handle_search_candidate_buffers(
3707 this: Model<Self>,
3708 envelope: TypedEnvelope<proto::FindSearchCandidates>,
3709 mut cx: AsyncAppContext,
3710 ) -> Result<proto::FindSearchCandidatesResponse> {
3711 let peer_id = envelope.original_sender_id()?;
3712 let message = envelope.payload;
3713 let query = SearchQuery::from_proto(
3714 message
3715 .query
3716 .ok_or_else(|| anyhow!("missing query field"))?,
3717 )?;
3718 let mut results = this.update(&mut cx, |this, cx| {
3719 this.find_search_candidate_buffers(&query, message.limit as _, cx)
3720 })?;
3721
3722 let mut response = proto::FindSearchCandidatesResponse {
3723 buffer_ids: Vec::new(),
3724 };
3725
3726 while let Some(buffer) = results.next().await {
3727 this.update(&mut cx, |this, cx| {
3728 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
3729 response.buffer_ids.push(buffer_id.to_proto());
3730 })?;
3731 }
3732
3733 Ok(response)
3734 }
3735
3736 async fn handle_open_buffer_by_id(
3737 this: Model<Self>,
3738 envelope: TypedEnvelope<proto::OpenBufferById>,
3739 mut cx: AsyncAppContext,
3740 ) -> Result<proto::OpenBufferResponse> {
3741 let peer_id = envelope.original_sender_id()?;
3742 let buffer_id = BufferId::new(envelope.payload.id)?;
3743 let buffer = this
3744 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
3745 .await?;
3746 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3747 }
3748
3749 async fn handle_open_buffer_by_path(
3750 this: Model<Self>,
3751 envelope: TypedEnvelope<proto::OpenBufferByPath>,
3752 mut cx: AsyncAppContext,
3753 ) -> Result<proto::OpenBufferResponse> {
3754 let peer_id = envelope.original_sender_id()?;
3755 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3756 let open_buffer = this.update(&mut cx, |this, cx| {
3757 this.open_buffer(
3758 ProjectPath {
3759 worktree_id,
3760 path: PathBuf::from(envelope.payload.path).into(),
3761 },
3762 cx,
3763 )
3764 })?;
3765
3766 let buffer = open_buffer.await?;
3767 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3768 }
3769
3770 async fn handle_open_new_buffer(
3771 this: Model<Self>,
3772 envelope: TypedEnvelope<proto::OpenNewBuffer>,
3773 mut cx: AsyncAppContext,
3774 ) -> Result<proto::OpenBufferResponse> {
3775 let buffer = this
3776 .update(&mut cx, |this, cx| this.create_buffer(cx))?
3777 .await?;
3778 let peer_id = envelope.original_sender_id()?;
3779
3780 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3781 }
3782
3783 fn respond_to_open_buffer_request(
3784 this: Model<Self>,
3785 buffer: Model<Buffer>,
3786 peer_id: proto::PeerId,
3787 cx: &mut AsyncAppContext,
3788 ) -> Result<proto::OpenBufferResponse> {
3789 this.update(cx, |this, cx| {
3790 let is_private = buffer
3791 .read(cx)
3792 .file()
3793 .map(|f| f.is_private())
3794 .unwrap_or_default();
3795 if is_private {
3796 Err(anyhow!(ErrorCode::UnsharedItem))
3797 } else {
3798 Ok(proto::OpenBufferResponse {
3799 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
3800 })
3801 }
3802 })?
3803 }
3804
3805 fn create_buffer_for_peer(
3806 &mut self,
3807 buffer: &Model<Buffer>,
3808 peer_id: proto::PeerId,
3809 cx: &mut AppContext,
3810 ) -> BufferId {
3811 self.buffer_store
3812 .update(cx, |buffer_store, cx| {
3813 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
3814 })
3815 .detach_and_log_err(cx);
3816 buffer.read(cx).remote_id()
3817 }
3818
3819 fn wait_for_remote_buffer(
3820 &mut self,
3821 id: BufferId,
3822 cx: &mut ModelContext<Self>,
3823 ) -> Task<Result<Model<Buffer>>> {
3824 self.buffer_store.update(cx, |buffer_store, cx| {
3825 buffer_store.wait_for_remote_buffer(id, cx)
3826 })
3827 }
3828
3829 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
3830 let project_id = match self.client_state {
3831 ProjectClientState::Remote {
3832 sharing_has_stopped,
3833 remote_id,
3834 ..
3835 } => {
3836 if sharing_has_stopped {
3837 return Task::ready(Err(anyhow!(
3838 "can't synchronize remote buffers on a readonly project"
3839 )));
3840 } else {
3841 remote_id
3842 }
3843 }
3844 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
3845 return Task::ready(Err(anyhow!(
3846 "can't synchronize remote buffers on a local project"
3847 )))
3848 }
3849 };
3850
3851 let client = self.client.clone();
3852 cx.spawn(move |this, mut cx| async move {
3853 let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
3854 this.buffer_store.read(cx).buffer_version_info(cx)
3855 })?;
3856 let response = client
3857 .request(proto::SynchronizeBuffers {
3858 project_id,
3859 buffers,
3860 })
3861 .await?;
3862
3863 let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
3864 response
3865 .buffers
3866 .into_iter()
3867 .map(|buffer| {
3868 let client = client.clone();
3869 let buffer_id = match BufferId::new(buffer.id) {
3870 Ok(id) => id,
3871 Err(e) => {
3872 return Task::ready(Err(e));
3873 }
3874 };
3875 let remote_version = language::proto::deserialize_version(&buffer.version);
3876 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
3877 let operations =
3878 buffer.read(cx).serialize_ops(Some(remote_version), cx);
3879 cx.background_executor().spawn(async move {
3880 let operations = operations.await;
3881 for chunk in split_operations(operations) {
3882 client
3883 .request(proto::UpdateBuffer {
3884 project_id,
3885 buffer_id: buffer_id.into(),
3886 operations: chunk,
3887 })
3888 .await?;
3889 }
3890 anyhow::Ok(())
3891 })
3892 } else {
3893 Task::ready(Ok(()))
3894 }
3895 })
3896 .collect::<Vec<_>>()
3897 })?;
3898
3899 // Any incomplete buffers have open requests waiting. Request that the host sends
3900 // creates these buffers for us again to unblock any waiting futures.
3901 for id in incomplete_buffer_ids {
3902 cx.background_executor()
3903 .spawn(client.request(proto::OpenBufferById {
3904 project_id,
3905 id: id.into(),
3906 }))
3907 .detach();
3908 }
3909
3910 futures::future::join_all(send_updates_for_buffers)
3911 .await
3912 .into_iter()
3913 .collect()
3914 })
3915 }
3916
3917 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
3918 self.worktree_store.read(cx).worktree_metadata_protos(cx)
3919 }
3920
3921 fn set_worktrees_from_proto(
3922 &mut self,
3923 worktrees: Vec<proto::WorktreeMetadata>,
3924 cx: &mut ModelContext<Project>,
3925 ) -> Result<()> {
3926 cx.notify();
3927 self.worktree_store.update(cx, |worktree_store, cx| {
3928 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
3929 })
3930 }
3931
3932 fn set_collaborators_from_proto(
3933 &mut self,
3934 messages: Vec<proto::Collaborator>,
3935 cx: &mut ModelContext<Self>,
3936 ) -> Result<()> {
3937 let mut collaborators = HashMap::default();
3938 for message in messages {
3939 let collaborator = Collaborator::from_proto(message)?;
3940 collaborators.insert(collaborator.peer_id, collaborator);
3941 }
3942 for old_peer_id in self.collaborators.keys() {
3943 if !collaborators.contains_key(old_peer_id) {
3944 cx.emit(Event::CollaboratorLeft(*old_peer_id));
3945 }
3946 }
3947 self.collaborators = collaborators;
3948 Ok(())
3949 }
3950
3951 pub fn language_servers<'a>(
3952 &'a self,
3953 cx: &'a AppContext,
3954 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
3955 self.lsp_store.read(cx).language_servers()
3956 }
3957
3958 pub fn supplementary_language_servers<'a>(
3959 &'a self,
3960 cx: &'a AppContext,
3961 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
3962 self.lsp_store.read(cx).supplementary_language_servers()
3963 }
3964
3965 pub fn language_server_for_id(
3966 &self,
3967 id: LanguageServerId,
3968 cx: &AppContext,
3969 ) -> Option<Arc<LanguageServer>> {
3970 self.lsp_store.read(cx).language_server_for_id(id)
3971 }
3972
3973 pub fn language_servers_for_buffer<'a>(
3974 &'a self,
3975 buffer: &'a Buffer,
3976 cx: &'a AppContext,
3977 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
3978 self.lsp_store
3979 .read(cx)
3980 .language_servers_for_buffer(buffer, cx)
3981 }
3982}
3983
3984fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
3985 code_actions
3986 .iter()
3987 .flat_map(|(kind, enabled)| {
3988 if *enabled {
3989 Some(kind.clone().into())
3990 } else {
3991 None
3992 }
3993 })
3994 .collect()
3995}
3996
3997pub struct PathMatchCandidateSet {
3998 pub snapshot: Snapshot,
3999 pub include_ignored: bool,
4000 pub include_root_name: bool,
4001 pub candidates: Candidates,
4002}
4003
4004pub enum Candidates {
4005 /// Only consider directories.
4006 Directories,
4007 /// Only consider files.
4008 Files,
4009 /// Consider directories and files.
4010 Entries,
4011}
4012
4013impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4014 type Candidates = PathMatchCandidateSetIter<'a>;
4015
4016 fn id(&self) -> usize {
4017 self.snapshot.id().to_usize()
4018 }
4019
4020 fn len(&self) -> usize {
4021 match self.candidates {
4022 Candidates::Files => {
4023 if self.include_ignored {
4024 self.snapshot.file_count()
4025 } else {
4026 self.snapshot.visible_file_count()
4027 }
4028 }
4029
4030 Candidates::Directories => {
4031 if self.include_ignored {
4032 self.snapshot.dir_count()
4033 } else {
4034 self.snapshot.visible_dir_count()
4035 }
4036 }
4037
4038 Candidates::Entries => {
4039 if self.include_ignored {
4040 self.snapshot.entry_count()
4041 } else {
4042 self.snapshot.visible_entry_count()
4043 }
4044 }
4045 }
4046 }
4047
4048 fn prefix(&self) -> Arc<str> {
4049 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
4050 self.snapshot.root_name().into()
4051 } else if self.include_root_name {
4052 format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
4053 } else {
4054 Arc::default()
4055 }
4056 }
4057
4058 fn candidates(&'a self, start: usize) -> Self::Candidates {
4059 PathMatchCandidateSetIter {
4060 traversal: match self.candidates {
4061 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
4062 Candidates::Files => self.snapshot.files(self.include_ignored, start),
4063 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
4064 },
4065 }
4066 }
4067}
4068
4069pub struct PathMatchCandidateSetIter<'a> {
4070 traversal: Traversal<'a>,
4071}
4072
4073impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
4074 type Item = fuzzy::PathMatchCandidate<'a>;
4075
4076 fn next(&mut self) -> Option<Self::Item> {
4077 self.traversal
4078 .next()
4079 .map(|entry| fuzzy::PathMatchCandidate {
4080 is_dir: entry.kind.is_dir(),
4081 path: &entry.path,
4082 char_bag: entry.char_bag,
4083 })
4084 }
4085}
4086
4087impl EventEmitter<Event> for Project {}
4088
4089impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
4090 fn from(val: &'a ProjectPath) -> Self {
4091 SettingsLocation {
4092 worktree_id: val.worktree_id,
4093 path: val.path.as_ref(),
4094 }
4095 }
4096}
4097
4098impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
4099 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
4100 Self {
4101 worktree_id,
4102 path: path.as_ref().into(),
4103 }
4104 }
4105}
4106
4107pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
4108 let mut path_components = path.components();
4109 let mut base_components = base.components();
4110 let mut components: Vec<Component> = Vec::new();
4111 loop {
4112 match (path_components.next(), base_components.next()) {
4113 (None, None) => break,
4114 (Some(a), None) => {
4115 components.push(a);
4116 components.extend(path_components.by_ref());
4117 break;
4118 }
4119 (None, _) => components.push(Component::ParentDir),
4120 (Some(a), Some(b)) if components.is_empty() && a == b => (),
4121 (Some(a), Some(Component::CurDir)) => components.push(a),
4122 (Some(a), Some(_)) => {
4123 components.push(Component::ParentDir);
4124 for _ in base_components {
4125 components.push(Component::ParentDir);
4126 }
4127 components.push(a);
4128 components.extend(path_components.by_ref());
4129 break;
4130 }
4131 }
4132 }
4133 components.iter().map(|c| c.as_os_str()).collect()
4134}
4135
4136fn resolve_path(base: &Path, path: &Path) -> PathBuf {
4137 let mut result = base.to_path_buf();
4138 for component in path.components() {
4139 match component {
4140 Component::ParentDir => {
4141 result.pop();
4142 }
4143 Component::CurDir => (),
4144 _ => result.push(component),
4145 }
4146 }
4147 result
4148}
4149
4150/// ResolvedPath is a path that has been resolved to either a ProjectPath
4151/// or an AbsPath and that *exists*.
4152#[derive(Debug, Clone)]
4153pub enum ResolvedPath {
4154 ProjectPath(ProjectPath),
4155 AbsPath(PathBuf),
4156}
4157
4158impl ResolvedPath {
4159 pub fn abs_path(&self) -> Option<&Path> {
4160 match self {
4161 Self::AbsPath(path) => Some(path.as_path()),
4162 _ => None,
4163 }
4164 }
4165
4166 pub fn project_path(&self) -> Option<&ProjectPath> {
4167 match self {
4168 Self::ProjectPath(path) => Some(&path),
4169 _ => None,
4170 }
4171 }
4172}
4173
4174impl Item for Buffer {
4175 fn try_open(
4176 project: &Model<Project>,
4177 path: &ProjectPath,
4178 cx: &mut AppContext,
4179 ) -> Option<Task<Result<Model<Self>>>> {
4180 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
4181 }
4182
4183 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
4184 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
4185 }
4186
4187 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
4188 File::from_dyn(self.file()).map(|file| ProjectPath {
4189 worktree_id: file.worktree_id(cx),
4190 path: file.path().clone(),
4191 })
4192 }
4193}
4194
4195impl Completion {
4196 /// A key that can be used to sort completions when displaying
4197 /// them to the user.
4198 pub fn sort_key(&self) -> (usize, &str) {
4199 let kind_key = match self.lsp_completion.kind {
4200 Some(lsp::CompletionItemKind::KEYWORD) => 0,
4201 Some(lsp::CompletionItemKind::VARIABLE) => 1,
4202 _ => 2,
4203 };
4204 (kind_key, &self.label.text[self.label.filter_range.clone()])
4205 }
4206
4207 /// Whether this completion is a snippet.
4208 pub fn is_snippet(&self) -> bool {
4209 self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
4210 }
4211
4212 /// Returns the corresponding color for this completion.
4213 ///
4214 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
4215 pub fn color(&self) -> Option<Hsla> {
4216 match self.lsp_completion.kind {
4217 Some(CompletionItemKind::COLOR) => color_extractor::extract_color(&self.lsp_completion),
4218 _ => None,
4219 }
4220 }
4221}
4222
4223#[derive(Debug)]
4224pub struct NoRepositoryError {}
4225
4226impl std::fmt::Display for NoRepositoryError {
4227 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4228 write!(f, "no git repository for worktree found")
4229 }
4230}
4231
4232impl std::error::Error for NoRepositoryError {}
4233
4234pub fn sort_worktree_entries(entries: &mut [Entry]) {
4235 entries.sort_by(|entry_a, entry_b| {
4236 compare_paths(
4237 (&entry_a.path, entry_a.is_file()),
4238 (&entry_b.path, entry_b.is_file()),
4239 )
4240 });
4241}