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