proto.rs

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