1#![allow(non_snake_case)]
2
3pub mod error;
4mod macros;
5mod typed_envelope;
6
7pub use error::*;
8pub use typed_envelope::*;
9
10use collections::HashMap;
11pub use prost::{DecodeError, Message};
12use serde::Serialize;
13use std::{
14 any::{Any, TypeId},
15 cmp,
16 fmt::{self, Debug},
17 iter, mem,
18 path::{Path, PathBuf},
19 sync::Arc,
20 time::{Duration, SystemTime, UNIX_EPOCH},
21};
22
23include!(concat!(env!("OUT_DIR"), "/zed.messages.rs"));
24
25pub const SSH_PEER_ID: PeerId = PeerId { owner_id: 0, id: 0 };
26pub const SSH_PROJECT_ID: u64 = 0;
27
28pub trait EnvelopedMessage: Clone + Debug + Serialize + Sized + Send + Sync + 'static {
29 const NAME: &'static str;
30 const PRIORITY: MessagePriority;
31 fn into_envelope(
32 self,
33 id: u32,
34 responding_to: Option<u32>,
35 original_sender_id: Option<PeerId>,
36 ) -> Envelope;
37 fn from_envelope(envelope: Envelope) -> Option<Self>;
38}
39
40pub trait EntityMessage: EnvelopedMessage {
41 type Entity;
42 fn remote_entity_id(&self) -> u64;
43}
44
45pub trait RequestMessage: EnvelopedMessage {
46 type Response: EnvelopedMessage;
47}
48
49pub trait AnyTypedEnvelope: 'static + Send + Sync {
50 fn payload_type_id(&self) -> TypeId;
51 fn payload_type_name(&self) -> &'static str;
52 fn as_any(&self) -> &dyn Any;
53 fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync>;
54 fn is_background(&self) -> bool;
55 fn original_sender_id(&self) -> Option<PeerId>;
56 fn sender_id(&self) -> PeerId;
57 fn message_id(&self) -> u32;
58}
59
60pub enum MessagePriority {
61 Foreground,
62 Background,
63}
64
65impl<T: EnvelopedMessage> AnyTypedEnvelope for TypedEnvelope<T> {
66 fn payload_type_id(&self) -> TypeId {
67 TypeId::of::<T>()
68 }
69
70 fn payload_type_name(&self) -> &'static str {
71 T::NAME
72 }
73
74 fn as_any(&self) -> &dyn Any {
75 self
76 }
77
78 fn into_any(self: Box<Self>) -> Box<dyn Any + Send + Sync> {
79 self
80 }
81
82 fn is_background(&self) -> bool {
83 matches!(T::PRIORITY, MessagePriority::Background)
84 }
85
86 fn original_sender_id(&self) -> Option<PeerId> {
87 self.original_sender_id
88 }
89
90 fn sender_id(&self) -> PeerId {
91 self.sender_id
92 }
93
94 fn message_id(&self) -> u32 {
95 self.message_id
96 }
97}
98
99impl PeerId {
100 pub fn from_u64(peer_id: u64) -> Self {
101 let owner_id = (peer_id >> 32) as u32;
102 let id = peer_id as u32;
103 Self { owner_id, id }
104 }
105
106 pub fn as_u64(self) -> u64 {
107 ((self.owner_id as u64) << 32) | (self.id as u64)
108 }
109}
110
111impl Copy for PeerId {}
112
113impl Eq for PeerId {}
114
115impl Ord for PeerId {
116 fn cmp(&self, other: &Self) -> cmp::Ordering {
117 self.owner_id
118 .cmp(&other.owner_id)
119 .then_with(|| self.id.cmp(&other.id))
120 }
121}
122
123impl PartialOrd for PeerId {
124 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
125 Some(self.cmp(other))
126 }
127}
128
129impl std::hash::Hash for PeerId {
130 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
131 self.owner_id.hash(state);
132 self.id.hash(state);
133 }
134}
135
136impl fmt::Display for PeerId {
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 write!(f, "{}/{}", self.owner_id, self.id)
139 }
140}
141
142pub trait FromProto {
143 fn from_proto(proto: String) -> Self;
144}
145
146pub trait ToProto {
147 fn to_proto(self) -> String;
148}
149
150impl FromProto for PathBuf {
151 #[cfg(target_os = "windows")]
152 fn from_proto(proto: String) -> Self {
153 proto.split("/").collect()
154 }
155
156 #[cfg(not(target_os = "windows"))]
157 fn from_proto(proto: String) -> Self {
158 PathBuf::from(proto)
159 }
160}
161
162impl FromProto for Arc<Path> {
163 fn from_proto(proto: String) -> Self {
164 PathBuf::from_proto(proto).into()
165 }
166}
167
168impl ToProto for PathBuf {
169 #[cfg(target_os = "windows")]
170 fn to_proto(self) -> String {
171 self.components()
172 .map(|comp| comp.as_os_str().to_string_lossy().to_string())
173 .collect::<Vec<_>>()
174 .join("/")
175 }
176
177 #[cfg(not(target_os = "windows"))]
178 fn to_proto(self) -> String {
179 self.to_string_lossy().to_string()
180 }
181}
182
183impl ToProto for &Path {
184 #[cfg(target_os = "windows")]
185 fn to_proto(self) -> String {
186 self.components()
187 .map(|comp| comp.as_os_str().to_string_lossy().to_string())
188 .collect::<Vec<_>>()
189 .join("/")
190 }
191
192 #[cfg(not(target_os = "windows"))]
193 fn to_proto(self) -> String {
194 self.to_string_lossy().to_string()
195 }
196}
197
198messages!(
199 (AcceptTermsOfService, Foreground),
200 (AcceptTermsOfServiceResponse, Foreground),
201 (Ack, Foreground),
202 (AckBufferOperation, Background),
203 (AckChannelMessage, Background),
204 (AddNotification, Foreground),
205 (AddProjectCollaborator, Foreground),
206 (ApplyCodeAction, Background),
207 (ApplyCodeActionResponse, Background),
208 (ApplyCompletionAdditionalEdits, Background),
209 (ApplyCompletionAdditionalEditsResponse, Background),
210 (BufferReloaded, Foreground),
211 (BufferSaved, Foreground),
212 (Call, Foreground),
213 (CallCanceled, Foreground),
214 (CancelCall, Foreground),
215 (ChannelMessageSent, Foreground),
216 (ChannelMessageUpdate, Foreground),
217 (Commit, Background),
218 (ComputeEmbeddings, Background),
219 (ComputeEmbeddingsResponse, Background),
220 (CopyProjectEntry, Foreground),
221 (CreateBufferForPeer, Foreground),
222 (CreateChannel, Foreground),
223 (CreateChannelResponse, Foreground),
224 (CreateProjectEntry, Foreground),
225 (CreateRoom, Foreground),
226 (CreateRoomResponse, Foreground),
227 (DeclineCall, Foreground),
228 (DeleteChannel, Foreground),
229 (DeleteNotification, Foreground),
230 (UpdateNotification, Foreground),
231 (DeleteProjectEntry, Foreground),
232 (EndStream, Foreground),
233 (Error, Foreground),
234 (ExpandProjectEntry, Foreground),
235 (ExpandProjectEntryResponse, Foreground),
236 (ExpandAllForProjectEntry, Foreground),
237 (ExpandAllForProjectEntryResponse, Foreground),
238 (Follow, Foreground),
239 (FollowResponse, Foreground),
240 (FormatBuffers, Foreground),
241 (FormatBuffersResponse, Foreground),
242 (FuzzySearchUsers, Foreground),
243 (GetCachedEmbeddings, Background),
244 (GetCachedEmbeddingsResponse, Background),
245 (GetChannelMembers, Foreground),
246 (GetChannelMembersResponse, Foreground),
247 (GetChannelMessages, Background),
248 (GetChannelMessagesById, Background),
249 (GetChannelMessagesResponse, Background),
250 (GetCodeActions, Background),
251 (GetCodeActionsResponse, Background),
252 (GetCompletions, Background),
253 (GetCompletionsResponse, Background),
254 (GetDefinition, Background),
255 (GetDefinitionResponse, Background),
256 (GetDeclaration, Background),
257 (GetDeclarationResponse, Background),
258 (GetDocumentHighlights, Background),
259 (GetDocumentHighlightsResponse, Background),
260 (GetHover, Background),
261 (GetHoverResponse, Background),
262 (GetNotifications, Foreground),
263 (GetNotificationsResponse, Foreground),
264 (GetPrivateUserInfo, Foreground),
265 (GetPrivateUserInfoResponse, Foreground),
266 (GetProjectSymbols, Background),
267 (GetProjectSymbolsResponse, Background),
268 (GetReferences, Background),
269 (GetReferencesResponse, Background),
270 (GetSignatureHelp, Background),
271 (GetSignatureHelpResponse, Background),
272 (GetSupermavenApiKey, Background),
273 (GetSupermavenApiKeyResponse, Background),
274 (GetTypeDefinition, Background),
275 (GetTypeDefinitionResponse, Background),
276 (GetImplementation, Background),
277 (GetImplementationResponse, Background),
278 (GetLlmToken, Background),
279 (GetLlmTokenResponse, Background),
280 (OpenUnstagedDiff, Foreground),
281 (OpenUnstagedDiffResponse, Foreground),
282 (OpenUncommittedDiff, Foreground),
283 (OpenUncommittedDiffResponse, Foreground),
284 (GetUsers, Foreground),
285 (Hello, Foreground),
286 (IncomingCall, Foreground),
287 (InlayHints, Background),
288 (InlayHintsResponse, Background),
289 (InviteChannelMember, Foreground),
290 (JoinChannel, Foreground),
291 (JoinChannelBuffer, Foreground),
292 (JoinChannelBufferResponse, Foreground),
293 (JoinChannelChat, Foreground),
294 (JoinChannelChatResponse, Foreground),
295 (JoinProject, Foreground),
296 (JoinProjectResponse, Foreground),
297 (JoinRoom, Foreground),
298 (JoinRoomResponse, Foreground),
299 (LeaveChannelBuffer, Background),
300 (LeaveChannelChat, Foreground),
301 (LeaveProject, Foreground),
302 (LeaveRoom, Foreground),
303 (MarkNotificationRead, Foreground),
304 (MoveChannel, Foreground),
305 (OnTypeFormatting, Background),
306 (OnTypeFormattingResponse, Background),
307 (OpenBufferById, Background),
308 (OpenBufferByPath, Background),
309 (OpenBufferForSymbol, Background),
310 (OpenBufferForSymbolResponse, Background),
311 (OpenBufferResponse, Background),
312 (OpenCommitMessageBuffer, Background),
313 (PerformRename, Background),
314 (PerformRenameResponse, Background),
315 (Ping, Foreground),
316 (PrepareRename, Background),
317 (PrepareRenameResponse, Background),
318 (ProjectEntryResponse, Foreground),
319 (CountLanguageModelTokens, Background),
320 (CountLanguageModelTokensResponse, Background),
321 (RefreshLlmToken, Background),
322 (RefreshInlayHints, Foreground),
323 (RejoinChannelBuffers, Foreground),
324 (RejoinChannelBuffersResponse, Foreground),
325 (RejoinRoom, Foreground),
326 (RejoinRoomResponse, Foreground),
327 (ReloadBuffers, Foreground),
328 (ReloadBuffersResponse, Foreground),
329 (RemoveChannelMember, Foreground),
330 (RemoveChannelMessage, Foreground),
331 (UpdateChannelMessage, Foreground),
332 (RemoveContact, Foreground),
333 (RemoveProjectCollaborator, Foreground),
334 (RenameChannel, Foreground),
335 (RenameChannelResponse, Foreground),
336 (RenameProjectEntry, Foreground),
337 (RequestContact, Foreground),
338 (ResolveCompletionDocumentation, Background),
339 (ResolveCompletionDocumentationResponse, Background),
340 (ResolveInlayHint, Background),
341 (ResolveInlayHintResponse, Background),
342 (RespondToChannelInvite, Foreground),
343 (RespondToContactRequest, Foreground),
344 (RoomUpdated, Foreground),
345 (SaveBuffer, Foreground),
346 (SetChannelMemberRole, Foreground),
347 (SetChannelVisibility, Foreground),
348 (SendChannelMessage, Background),
349 (SendChannelMessageResponse, Background),
350 (ShareProject, Foreground),
351 (ShareProjectResponse, Foreground),
352 (ShowContacts, Foreground),
353 (Stage, Background),
354 (StartLanguageServer, Foreground),
355 (SubscribeToChannels, Foreground),
356 (SynchronizeBuffers, Foreground),
357 (SynchronizeBuffersResponse, Foreground),
358 (TaskContextForLocation, Background),
359 (TaskContext, Background),
360 (Test, Foreground),
361 (Unfollow, Foreground),
362 (UnshareProject, Foreground),
363 (Unstage, Background),
364 (UpdateBuffer, Foreground),
365 (UpdateBufferFile, Foreground),
366 (UpdateChannelBuffer, Foreground),
367 (UpdateChannelBufferCollaborators, Foreground),
368 (UpdateChannels, Foreground),
369 (UpdateUserChannels, Foreground),
370 (UpdateContacts, Foreground),
371 (UpdateDiagnosticSummary, Foreground),
372 (UpdateDiffBases, Foreground),
373 (UpdateFollowers, Foreground),
374 (UpdateInviteInfo, Foreground),
375 (UpdateLanguageServer, Foreground),
376 (UpdateParticipantLocation, Foreground),
377 (UpdateProject, Foreground),
378 (UpdateProjectCollaborator, Foreground),
379 (UpdateUserPlan, Foreground),
380 (UpdateWorktree, Foreground),
381 (UpdateWorktreeSettings, Foreground),
382 (UsersResponse, Foreground),
383 (LspExtExpandMacro, Background),
384 (LspExtExpandMacroResponse, Background),
385 (LspExtOpenDocs, Background),
386 (LspExtOpenDocsResponse, Background),
387 (SetRoomParticipantRole, Foreground),
388 (BlameBuffer, Foreground),
389 (BlameBufferResponse, Foreground),
390 (RejoinRemoteProjects, Foreground),
391 (RejoinRemoteProjectsResponse, Foreground),
392 (MultiLspQuery, Background),
393 (MultiLspQueryResponse, Background),
394 (ListRemoteDirectory, Background),
395 (ListRemoteDirectoryResponse, Background),
396 (OpenNewBuffer, Foreground),
397 (RestartLanguageServers, Foreground),
398 (LinkedEditingRange, Background),
399 (LinkedEditingRangeResponse, Background),
400 (AdvertiseContexts, Foreground),
401 (OpenContext, Foreground),
402 (OpenContextResponse, Foreground),
403 (CreateContext, Foreground),
404 (CreateContextResponse, Foreground),
405 (UpdateContext, Foreground),
406 (SynchronizeContexts, Foreground),
407 (SynchronizeContextsResponse, Foreground),
408 (LspExtSwitchSourceHeader, Background),
409 (LspExtSwitchSourceHeaderResponse, Background),
410 (AddWorktree, Foreground),
411 (AddWorktreeResponse, Foreground),
412 (FindSearchCandidates, Background),
413 (FindSearchCandidatesResponse, Background),
414 (CloseBuffer, Foreground),
415 (ShutdownRemoteServer, Foreground),
416 (RemoveWorktree, Foreground),
417 (LanguageServerLog, Foreground),
418 (Toast, Background),
419 (HideToast, Background),
420 (OpenServerSettings, Foreground),
421 (GetPermalinkToLine, Foreground),
422 (GetPermalinkToLineResponse, Foreground),
423 (FlushBufferedMessages, Foreground),
424 (LanguageServerPromptRequest, Foreground),
425 (LanguageServerPromptResponse, Foreground),
426 (GitBranches, Background),
427 (GitBranchesResponse, Background),
428 (UpdateGitBranch, Background),
429 (ListToolchains, Foreground),
430 (ListToolchainsResponse, Foreground),
431 (ActivateToolchain, Foreground),
432 (ActiveToolchain, Foreground),
433 (ActiveToolchainResponse, Foreground),
434 (GetPathMetadata, Background),
435 (GetPathMetadataResponse, Background),
436 (GetPanicFiles, Background),
437 (GetPanicFilesResponse, Background),
438 (CancelLanguageServerWork, Foreground),
439 (SyncExtensions, Background),
440 (SyncExtensionsResponse, Background),
441 (InstallExtension, Background),
442 (RegisterBufferWithLanguageServers, Background),
443 (GitReset, Background),
444 (GitCheckoutFiles, Background),
445 (GitShow, Background),
446 (GitCommitDetails, Background),
447 (SetIndexText, Background),
448 (Push, Background),
449 (Fetch, Background),
450 (GetRemotes, Background),
451 (GetRemotesResponse, Background),
452 (Pull, Background),
453);
454
455request_messages!(
456 (AcceptTermsOfService, AcceptTermsOfServiceResponse),
457 (ApplyCodeAction, ApplyCodeActionResponse),
458 (
459 ApplyCompletionAdditionalEdits,
460 ApplyCompletionAdditionalEditsResponse
461 ),
462 (Call, Ack),
463 (CancelCall, Ack),
464 (Commit, Ack),
465 (CopyProjectEntry, ProjectEntryResponse),
466 (ComputeEmbeddings, ComputeEmbeddingsResponse),
467 (CreateChannel, CreateChannelResponse),
468 (CreateProjectEntry, ProjectEntryResponse),
469 (CreateRoom, CreateRoomResponse),
470 (DeclineCall, Ack),
471 (DeleteChannel, Ack),
472 (DeleteProjectEntry, ProjectEntryResponse),
473 (ExpandProjectEntry, ExpandProjectEntryResponse),
474 (ExpandAllForProjectEntry, ExpandAllForProjectEntryResponse),
475 (Follow, FollowResponse),
476 (FormatBuffers, FormatBuffersResponse),
477 (FuzzySearchUsers, UsersResponse),
478 (GetCachedEmbeddings, GetCachedEmbeddingsResponse),
479 (GetChannelMembers, GetChannelMembersResponse),
480 (GetChannelMessages, GetChannelMessagesResponse),
481 (GetChannelMessagesById, GetChannelMessagesResponse),
482 (GetCodeActions, GetCodeActionsResponse),
483 (GetCompletions, GetCompletionsResponse),
484 (GetDefinition, GetDefinitionResponse),
485 (GetDeclaration, GetDeclarationResponse),
486 (GetImplementation, GetImplementationResponse),
487 (GetDocumentHighlights, GetDocumentHighlightsResponse),
488 (GetHover, GetHoverResponse),
489 (GetLlmToken, GetLlmTokenResponse),
490 (GetNotifications, GetNotificationsResponse),
491 (GetPrivateUserInfo, GetPrivateUserInfoResponse),
492 (GetProjectSymbols, GetProjectSymbolsResponse),
493 (GetReferences, GetReferencesResponse),
494 (GetSignatureHelp, GetSignatureHelpResponse),
495 (OpenUnstagedDiff, OpenUnstagedDiffResponse),
496 (OpenUncommittedDiff, OpenUncommittedDiffResponse),
497 (GetSupermavenApiKey, GetSupermavenApiKeyResponse),
498 (GetTypeDefinition, GetTypeDefinitionResponse),
499 (LinkedEditingRange, LinkedEditingRangeResponse),
500 (ListRemoteDirectory, ListRemoteDirectoryResponse),
501 (GetUsers, UsersResponse),
502 (IncomingCall, Ack),
503 (InlayHints, InlayHintsResponse),
504 (InviteChannelMember, Ack),
505 (JoinChannel, JoinRoomResponse),
506 (JoinChannelBuffer, JoinChannelBufferResponse),
507 (JoinChannelChat, JoinChannelChatResponse),
508 (JoinProject, JoinProjectResponse),
509 (JoinRoom, JoinRoomResponse),
510 (LeaveChannelBuffer, Ack),
511 (LeaveRoom, Ack),
512 (MarkNotificationRead, Ack),
513 (MoveChannel, Ack),
514 (OnTypeFormatting, OnTypeFormattingResponse),
515 (OpenBufferById, OpenBufferResponse),
516 (OpenBufferByPath, OpenBufferResponse),
517 (OpenBufferForSymbol, OpenBufferForSymbolResponse),
518 (OpenCommitMessageBuffer, OpenBufferResponse),
519 (OpenNewBuffer, OpenBufferResponse),
520 (PerformRename, PerformRenameResponse),
521 (Ping, Ack),
522 (PrepareRename, PrepareRenameResponse),
523 (CountLanguageModelTokens, CountLanguageModelTokensResponse),
524 (RefreshInlayHints, Ack),
525 (RejoinChannelBuffers, RejoinChannelBuffersResponse),
526 (RejoinRoom, RejoinRoomResponse),
527 (ReloadBuffers, ReloadBuffersResponse),
528 (RemoveChannelMember, Ack),
529 (RemoveChannelMessage, Ack),
530 (UpdateChannelMessage, Ack),
531 (RemoveContact, Ack),
532 (RenameChannel, RenameChannelResponse),
533 (RenameProjectEntry, ProjectEntryResponse),
534 (RequestContact, Ack),
535 (
536 ResolveCompletionDocumentation,
537 ResolveCompletionDocumentationResponse
538 ),
539 (ResolveInlayHint, ResolveInlayHintResponse),
540 (RespondToChannelInvite, Ack),
541 (RespondToContactRequest, Ack),
542 (SaveBuffer, BufferSaved),
543 (Stage, Ack),
544 (FindSearchCandidates, FindSearchCandidatesResponse),
545 (SendChannelMessage, SendChannelMessageResponse),
546 (SetChannelMemberRole, Ack),
547 (SetChannelVisibility, Ack),
548 (ShareProject, ShareProjectResponse),
549 (SynchronizeBuffers, SynchronizeBuffersResponse),
550 (TaskContextForLocation, TaskContext),
551 (Test, Test),
552 (Unstage, Ack),
553 (UpdateBuffer, Ack),
554 (UpdateParticipantLocation, Ack),
555 (UpdateProject, Ack),
556 (UpdateWorktree, Ack),
557 (LspExtExpandMacro, LspExtExpandMacroResponse),
558 (LspExtOpenDocs, LspExtOpenDocsResponse),
559 (SetRoomParticipantRole, Ack),
560 (BlameBuffer, BlameBufferResponse),
561 (RejoinRemoteProjects, RejoinRemoteProjectsResponse),
562 (MultiLspQuery, MultiLspQueryResponse),
563 (RestartLanguageServers, Ack),
564 (OpenContext, OpenContextResponse),
565 (CreateContext, CreateContextResponse),
566 (SynchronizeContexts, SynchronizeContextsResponse),
567 (LspExtSwitchSourceHeader, LspExtSwitchSourceHeaderResponse),
568 (AddWorktree, AddWorktreeResponse),
569 (ShutdownRemoteServer, Ack),
570 (RemoveWorktree, Ack),
571 (OpenServerSettings, OpenBufferResponse),
572 (GetPermalinkToLine, GetPermalinkToLineResponse),
573 (FlushBufferedMessages, Ack),
574 (LanguageServerPromptRequest, LanguageServerPromptResponse),
575 (GitBranches, GitBranchesResponse),
576 (UpdateGitBranch, Ack),
577 (ListToolchains, ListToolchainsResponse),
578 (ActivateToolchain, Ack),
579 (ActiveToolchain, ActiveToolchainResponse),
580 (GetPathMetadata, GetPathMetadataResponse),
581 (GetPanicFiles, GetPanicFilesResponse),
582 (CancelLanguageServerWork, Ack),
583 (SyncExtensions, SyncExtensionsResponse),
584 (InstallExtension, Ack),
585 (RegisterBufferWithLanguageServers, Ack),
586 (GitShow, GitCommitDetails),
587 (GitReset, Ack),
588 (GitCheckoutFiles, Ack),
589 (SetIndexText, Ack),
590 (Push, Ack),
591 (Fetch, Ack),
592 (GetRemotes, GetRemotesResponse),
593 (Pull, Ack),
594);
595
596entity_messages!(
597 {project_id, ShareProject},
598 AddProjectCollaborator,
599 AddWorktree,
600 ApplyCodeAction,
601 ApplyCompletionAdditionalEdits,
602 BlameBuffer,
603 BufferReloaded,
604 BufferSaved,
605 CloseBuffer,
606 Commit,
607 CopyProjectEntry,
608 CreateBufferForPeer,
609 CreateProjectEntry,
610 DeleteProjectEntry,
611 ExpandProjectEntry,
612 ExpandAllForProjectEntry,
613 FindSearchCandidates,
614 FormatBuffers,
615 GetCodeActions,
616 GetCompletions,
617 GetDefinition,
618 GetDeclaration,
619 GetImplementation,
620 GetDocumentHighlights,
621 GetHover,
622 GetProjectSymbols,
623 GetReferences,
624 GetSignatureHelp,
625 OpenUnstagedDiff,
626 OpenUncommittedDiff,
627 GetTypeDefinition,
628 InlayHints,
629 JoinProject,
630 LeaveProject,
631 LinkedEditingRange,
632 MultiLspQuery,
633 RestartLanguageServers,
634 OnTypeFormatting,
635 OpenNewBuffer,
636 OpenBufferById,
637 OpenBufferByPath,
638 OpenBufferForSymbol,
639 OpenCommitMessageBuffer,
640 PerformRename,
641 PrepareRename,
642 RefreshInlayHints,
643 ReloadBuffers,
644 RemoveProjectCollaborator,
645 RenameProjectEntry,
646 ResolveCompletionDocumentation,
647 ResolveInlayHint,
648 SaveBuffer,
649 Stage,
650 StartLanguageServer,
651 SynchronizeBuffers,
652 TaskContextForLocation,
653 UnshareProject,
654 Unstage,
655 UpdateBuffer,
656 UpdateBufferFile,
657 UpdateDiagnosticSummary,
658 UpdateDiffBases,
659 UpdateLanguageServer,
660 UpdateProject,
661 UpdateProjectCollaborator,
662 UpdateWorktree,
663 UpdateWorktreeSettings,
664 LspExtExpandMacro,
665 LspExtOpenDocs,
666 AdvertiseContexts,
667 OpenContext,
668 CreateContext,
669 UpdateContext,
670 SynchronizeContexts,
671 LspExtSwitchSourceHeader,
672 LanguageServerLog,
673 Toast,
674 HideToast,
675 OpenServerSettings,
676 GetPermalinkToLine,
677 LanguageServerPromptRequest,
678 GitBranches,
679 UpdateGitBranch,
680 ListToolchains,
681 ActivateToolchain,
682 ActiveToolchain,
683 GetPathMetadata,
684 CancelLanguageServerWork,
685 RegisterBufferWithLanguageServers,
686 GitShow,
687 GitReset,
688 GitCheckoutFiles,
689 SetIndexText,
690 Push,
691 Fetch,
692 GetRemotes,
693 Pull,
694);
695
696entity_messages!(
697 {channel_id, Channel},
698 ChannelMessageSent,
699 ChannelMessageUpdate,
700 RemoveChannelMessage,
701 UpdateChannelMessage,
702 UpdateChannelBuffer,
703 UpdateChannelBufferCollaborators,
704);
705
706impl From<Timestamp> for SystemTime {
707 fn from(val: Timestamp) -> Self {
708 UNIX_EPOCH
709 .checked_add(Duration::new(val.seconds, val.nanos))
710 .unwrap()
711 }
712}
713
714impl From<SystemTime> for Timestamp {
715 fn from(time: SystemTime) -> Self {
716 let duration = time.duration_since(UNIX_EPOCH).unwrap();
717 Self {
718 seconds: duration.as_secs(),
719 nanos: duration.subsec_nanos(),
720 }
721 }
722}
723
724impl From<u128> for Nonce {
725 fn from(nonce: u128) -> Self {
726 let upper_half = (nonce >> 64) as u64;
727 let lower_half = nonce as u64;
728 Self {
729 upper_half,
730 lower_half,
731 }
732 }
733}
734
735impl From<Nonce> for u128 {
736 fn from(nonce: Nonce) -> Self {
737 let upper_half = (nonce.upper_half as u128) << 64;
738 let lower_half = nonce.lower_half as u128;
739 upper_half | lower_half
740 }
741}
742
743#[cfg(any(test, feature = "test-support"))]
744pub const MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE: usize = 2;
745#[cfg(not(any(test, feature = "test-support")))]
746pub const MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE: usize = 256;
747
748pub fn split_worktree_update(mut message: UpdateWorktree) -> impl Iterator<Item = UpdateWorktree> {
749 let mut done_files = false;
750
751 let mut repository_map = message
752 .updated_repositories
753 .into_iter()
754 .map(|repo| (repo.work_directory_id, repo))
755 .collect::<HashMap<_, _>>();
756
757 iter::from_fn(move || {
758 if done_files {
759 return None;
760 }
761
762 let updated_entries_chunk_size = cmp::min(
763 message.updated_entries.len(),
764 MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE,
765 );
766 let updated_entries: Vec<_> = message
767 .updated_entries
768 .drain(..updated_entries_chunk_size)
769 .collect();
770
771 let removed_entries_chunk_size = cmp::min(
772 message.removed_entries.len(),
773 MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE,
774 );
775 let removed_entries = message
776 .removed_entries
777 .drain(..removed_entries_chunk_size)
778 .collect();
779
780 done_files = message.updated_entries.is_empty() && message.removed_entries.is_empty();
781
782 let mut updated_repositories = Vec::new();
783
784 if !repository_map.is_empty() {
785 for entry in &updated_entries {
786 if let Some(repo) = repository_map.remove(&entry.id) {
787 updated_repositories.push(repo);
788 }
789 }
790 }
791
792 let removed_repositories = if done_files {
793 mem::take(&mut message.removed_repositories)
794 } else {
795 Default::default()
796 };
797
798 if done_files {
799 updated_repositories.extend(mem::take(&mut repository_map).into_values());
800 }
801
802 Some(UpdateWorktree {
803 project_id: message.project_id,
804 worktree_id: message.worktree_id,
805 root_name: message.root_name.clone(),
806 abs_path: message.abs_path.clone(),
807 updated_entries,
808 removed_entries,
809 scan_id: message.scan_id,
810 is_last_update: done_files && message.is_last_update,
811 updated_repositories,
812 removed_repositories,
813 })
814 })
815}
816
817#[cfg(test)]
818mod tests {
819 use super::*;
820
821 #[test]
822 fn test_converting_peer_id_from_and_to_u64() {
823 let peer_id = PeerId {
824 owner_id: 10,
825 id: 3,
826 };
827 assert_eq!(PeerId::from_u64(peer_id.as_u64()), peer_id);
828 let peer_id = PeerId {
829 owner_id: u32::MAX,
830 id: 3,
831 };
832 assert_eq!(PeerId::from_u64(peer_id.as_u64()), peer_id);
833 let peer_id = PeerId {
834 owner_id: 10,
835 id: u32::MAX,
836 };
837 assert_eq!(PeerId::from_u64(peer_id.as_u64()), peer_id);
838 let peer_id = PeerId {
839 owner_id: u32::MAX,
840 id: u32::MAX,
841 };
842 assert_eq!(PeerId::from_u64(peer_id.as_u64()), peer_id);
843 }
844
845 #[test]
846 #[cfg(target_os = "windows")]
847 fn test_proto() {
848 fn generate_proto_path(path: PathBuf) -> PathBuf {
849 let proto = path.to_proto();
850 PathBuf::from_proto(proto)
851 }
852
853 let path = PathBuf::from("C:\\foo\\bar");
854 assert_eq!(path, generate_proto_path(path.clone()));
855
856 let path = PathBuf::from("C:/foo/bar/");
857 assert_eq!(path, generate_proto_path(path.clone()));
858
859 let path = PathBuf::from("C:/foo\\bar\\");
860 assert_eq!(path, generate_proto_path(path.clone()));
861 }
862}