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    (AddNotification, Foreground),
204    (AddProjectCollaborator, Foreground),
205    (ApplyCodeAction, Background),
206    (ApplyCodeActionResponse, Background),
207    (ApplyCompletionAdditionalEdits, Background),
208    (ApplyCompletionAdditionalEditsResponse, Background),
209    (BufferReloaded, Foreground),
210    (BufferSaved, Foreground),
211    (Call, Foreground),
212    (CallCanceled, Foreground),
213    (CancelCall, Foreground),
214    (ChannelMessageSent, Foreground),
215    (ChannelMessageUpdate, Foreground),
216    (Commit, Background),
217    (ComputeEmbeddings, Background),
218    (ComputeEmbeddingsResponse, Background),
219    (CopyProjectEntry, Foreground),
220    (CreateBufferForPeer, Foreground),
221    (CreateChannel, Foreground),
222    (CreateChannelResponse, Foreground),
223    (CreateProjectEntry, Foreground),
224    (CreateRoom, Foreground),
225    (CreateRoomResponse, Foreground),
226    (DeclineCall, Foreground),
227    (DeleteChannel, Foreground),
228    (DeleteNotification, Foreground),
229    (UpdateNotification, Foreground),
230    (DeleteProjectEntry, Foreground),
231    (EndStream, Foreground),
232    (Error, Foreground),
233    (ExpandProjectEntry, Foreground),
234    (ExpandProjectEntryResponse, Foreground),
235    (ExpandAllForProjectEntry, Foreground),
236    (ExpandAllForProjectEntryResponse, Foreground),
237    (Follow, Foreground),
238    (FollowResponse, Foreground),
239    (FormatBuffers, Foreground),
240    (FormatBuffersResponse, Foreground),
241    (FuzzySearchUsers, Foreground),
242    (GetCachedEmbeddings, Background),
243    (GetCachedEmbeddingsResponse, Background),
244    (GetChannelMembers, Foreground),
245    (GetChannelMembersResponse, Foreground),
246    (GetChannelMessages, Background),
247    (GetChannelMessagesById, Background),
248    (GetChannelMessagesResponse, Background),
249    (GetCodeActions, Background),
250    (GetCodeActionsResponse, Background),
251    (GetCompletions, Background),
252    (GetCompletionsResponse, Background),
253    (GetDefinition, Background),
254    (GetDefinitionResponse, Background),
255    (GetDeclaration, Background),
256    (GetDeclarationResponse, Background),
257    (GetDocumentHighlights, Background),
258    (GetDocumentHighlightsResponse, Background),
259    (GetHover, Background),
260    (GetHoverResponse, Background),
261    (GetNotifications, Foreground),
262    (GetNotificationsResponse, Foreground),
263    (GetPrivateUserInfo, Foreground),
264    (GetPrivateUserInfoResponse, Foreground),
265    (GetProjectSymbols, Background),
266    (GetProjectSymbolsResponse, Background),
267    (GetReferences, Background),
268    (GetReferencesResponse, Background),
269    (GetSignatureHelp, Background),
270    (GetSignatureHelpResponse, Background),
271    (GetSupermavenApiKey, Background),
272    (GetSupermavenApiKeyResponse, Background),
273    (GetTypeDefinition, Background),
274    (GetTypeDefinitionResponse, Background),
275    (GetImplementation, Background),
276    (GetImplementationResponse, Background),
277    (GetLlmToken, Background),
278    (GetLlmTokenResponse, Background),
279    (OpenUnstagedDiff, Foreground),
280    (OpenUnstagedDiffResponse, Foreground),
281    (OpenUncommittedDiff, Foreground),
282    (OpenUncommittedDiffResponse, Foreground),
283    (GetUsers, Foreground),
284    (Hello, Foreground),
285    (IncomingCall, Foreground),
286    (InlayHints, Background),
287    (InlayHintsResponse, Background),
288    (InviteChannelMember, Foreground),
289    (JoinChannel, Foreground),
290    (JoinChannelBuffer, Foreground),
291    (JoinChannelBufferResponse, Foreground),
292    (JoinChannelChat, Foreground),
293    (JoinChannelChatResponse, Foreground),
294    (JoinProject, Foreground),
295    (JoinProjectResponse, Foreground),
296    (JoinRoom, Foreground),
297    (JoinRoomResponse, Foreground),
298    (LeaveChannelBuffer, Background),
299    (LeaveChannelChat, Foreground),
300    (LeaveProject, Foreground),
301    (LeaveRoom, Foreground),
302    (MarkNotificationRead, Foreground),
303    (MoveChannel, Foreground),
304    (OnTypeFormatting, Background),
305    (OnTypeFormattingResponse, Background),
306    (OpenBufferById, Background),
307    (OpenBufferByPath, Background),
308    (OpenBufferForSymbol, Background),
309    (OpenBufferForSymbolResponse, Background),
310    (OpenBufferResponse, Background),
311    (OpenCommitMessageBuffer, Background),
312    (PerformRename, Background),
313    (PerformRenameResponse, Background),
314    (Ping, Foreground),
315    (PrepareRename, Background),
316    (PrepareRenameResponse, Background),
317    (ProjectEntryResponse, Foreground),
318    (CountLanguageModelTokens, Background),
319    (CountLanguageModelTokensResponse, Background),
320    (RefreshLlmToken, Background),
321    (RefreshInlayHints, Foreground),
322    (RejoinChannelBuffers, Foreground),
323    (RejoinChannelBuffersResponse, Foreground),
324    (RejoinRoom, Foreground),
325    (RejoinRoomResponse, Foreground),
326    (ReloadBuffers, Foreground),
327    (ReloadBuffersResponse, Foreground),
328    (RemoveChannelMember, Foreground),
329    (RemoveChannelMessage, Foreground),
330    (UpdateChannelMessage, Foreground),
331    (RemoveContact, Foreground),
332    (RemoveProjectCollaborator, Foreground),
333    (RenameChannel, Foreground),
334    (RenameChannelResponse, Foreground),
335    (RenameProjectEntry, Foreground),
336    (RequestContact, Foreground),
337    (ResolveCompletionDocumentation, Background),
338    (ResolveCompletionDocumentationResponse, Background),
339    (ResolveInlayHint, Background),
340    (ResolveInlayHintResponse, Background),
341    (RespondToChannelInvite, Foreground),
342    (RespondToContactRequest, Foreground),
343    (RoomUpdated, Foreground),
344    (SaveBuffer, Foreground),
345    (SetChannelMemberRole, Foreground),
346    (SetChannelVisibility, Foreground),
347    (SendChannelMessage, Background),
348    (SendChannelMessageResponse, Background),
349    (ShareProject, Foreground),
350    (ShareProjectResponse, Foreground),
351    (ShowContacts, Foreground),
352    (Stage, Background),
353    (StartLanguageServer, Foreground),
354    (SubscribeToChannels, Foreground),
355    (SynchronizeBuffers, Foreground),
356    (SynchronizeBuffersResponse, Foreground),
357    (TaskContextForLocation, Background),
358    (TaskContext, Background),
359    (Test, Foreground),
360    (Unfollow, Foreground),
361    (UnshareProject, Foreground),
362    (Unstage, Background),
363    (UpdateBuffer, Foreground),
364    (UpdateBufferFile, Foreground),
365    (UpdateChannelBuffer, Foreground),
366    (UpdateChannelBufferCollaborators, Foreground),
367    (UpdateChannels, Foreground),
368    (UpdateUserChannels, Foreground),
369    (UpdateContacts, Foreground),
370    (UpdateDiagnosticSummary, Foreground),
371    (UpdateDiffBases, Foreground),
372    (UpdateFollowers, Foreground),
373    (UpdateInviteInfo, Foreground),
374    (UpdateLanguageServer, Foreground),
375    (UpdateParticipantLocation, Foreground),
376    (UpdateProject, Foreground),
377    (UpdateProjectCollaborator, Foreground),
378    (UpdateUserPlan, Foreground),
379    (UpdateWorktree, Foreground),
380    (UpdateWorktreeSettings, Foreground),
381    (UsersResponse, Foreground),
382    (LspExtExpandMacro, Background),
383    (LspExtExpandMacroResponse, Background),
384    (LspExtOpenDocs, Background),
385    (LspExtOpenDocsResponse, Background),
386    (SetRoomParticipantRole, Foreground),
387    (BlameBuffer, Foreground),
388    (BlameBufferResponse, Foreground),
389    (RejoinRemoteProjects, Foreground),
390    (RejoinRemoteProjectsResponse, Foreground),
391    (MultiLspQuery, Background),
392    (MultiLspQueryResponse, Background),
393    (ListRemoteDirectory, Background),
394    (ListRemoteDirectoryResponse, Background),
395    (OpenNewBuffer, Foreground),
396    (RestartLanguageServers, Foreground),
397    (LinkedEditingRange, Background),
398    (LinkedEditingRangeResponse, Background),
399    (AdvertiseContexts, Foreground),
400    (OpenContext, Foreground),
401    (OpenContextResponse, Foreground),
402    (CreateContext, Foreground),
403    (CreateContextResponse, Foreground),
404    (UpdateContext, Foreground),
405    (SynchronizeContexts, Foreground),
406    (SynchronizeContextsResponse, Foreground),
407    (LspExtSwitchSourceHeader, Background),
408    (LspExtSwitchSourceHeaderResponse, Background),
409    (AddWorktree, Foreground),
410    (AddWorktreeResponse, Foreground),
411    (FindSearchCandidates, Background),
412    (FindSearchCandidatesResponse, Background),
413    (CloseBuffer, Foreground),
414    (ShutdownRemoteServer, Foreground),
415    (RemoveWorktree, Foreground),
416    (LanguageServerLog, Foreground),
417    (Toast, Background),
418    (HideToast, Background),
419    (OpenServerSettings, Foreground),
420    (GetPermalinkToLine, Foreground),
421    (GetPermalinkToLineResponse, Foreground),
422    (FlushBufferedMessages, Foreground),
423    (LanguageServerPromptRequest, Foreground),
424    (LanguageServerPromptResponse, Foreground),
425    (GitBranches, Background),
426    (GitBranchesResponse, Background),
427    (UpdateGitBranch, Background),
428    (ListToolchains, Foreground),
429    (ListToolchainsResponse, Foreground),
430    (ActivateToolchain, Foreground),
431    (ActiveToolchain, Foreground),
432    (ActiveToolchainResponse, Foreground),
433    (GetPathMetadata, Background),
434    (GetPathMetadataResponse, Background),
435    (GetPanicFiles, Background),
436    (GetPanicFilesResponse, Background),
437    (CancelLanguageServerWork, Foreground),
438    (SyncExtensions, Background),
439    (SyncExtensionsResponse, Background),
440    (InstallExtension, Background),
441    (RegisterBufferWithLanguageServers, Background),
442    (GitReset, Background),
443    (GitCheckoutFiles, Background),
444    (GitShow, Background),
445    (GitCommitDetails, Background),
446    (SetIndexText, Background),
447    (Push, Background),
448    (Fetch, Background),
449    (GetRemotes, Background),
450    (GetRemotesResponse, Background),
451    (Pull, Background),
452);
453
454request_messages!(
455    (AcceptTermsOfService, AcceptTermsOfServiceResponse),
456    (ApplyCodeAction, ApplyCodeActionResponse),
457    (
458        ApplyCompletionAdditionalEdits,
459        ApplyCompletionAdditionalEditsResponse
460    ),
461    (Call, Ack),
462    (CancelCall, Ack),
463    (Commit, Ack),
464    (CopyProjectEntry, ProjectEntryResponse),
465    (ComputeEmbeddings, ComputeEmbeddingsResponse),
466    (CreateChannel, CreateChannelResponse),
467    (CreateProjectEntry, ProjectEntryResponse),
468    (CreateRoom, CreateRoomResponse),
469    (DeclineCall, Ack),
470    (DeleteChannel, Ack),
471    (DeleteProjectEntry, ProjectEntryResponse),
472    (ExpandProjectEntry, ExpandProjectEntryResponse),
473    (ExpandAllForProjectEntry, ExpandAllForProjectEntryResponse),
474    (Follow, FollowResponse),
475    (FormatBuffers, FormatBuffersResponse),
476    (FuzzySearchUsers, UsersResponse),
477    (GetCachedEmbeddings, GetCachedEmbeddingsResponse),
478    (GetChannelMembers, GetChannelMembersResponse),
479    (GetChannelMessages, GetChannelMessagesResponse),
480    (GetChannelMessagesById, GetChannelMessagesResponse),
481    (GetCodeActions, GetCodeActionsResponse),
482    (GetCompletions, GetCompletionsResponse),
483    (GetDefinition, GetDefinitionResponse),
484    (GetDeclaration, GetDeclarationResponse),
485    (GetImplementation, GetImplementationResponse),
486    (GetDocumentHighlights, GetDocumentHighlightsResponse),
487    (GetHover, GetHoverResponse),
488    (GetLlmToken, GetLlmTokenResponse),
489    (GetNotifications, GetNotificationsResponse),
490    (GetPrivateUserInfo, GetPrivateUserInfoResponse),
491    (GetProjectSymbols, GetProjectSymbolsResponse),
492    (GetReferences, GetReferencesResponse),
493    (GetSignatureHelp, GetSignatureHelpResponse),
494    (OpenUnstagedDiff, OpenUnstagedDiffResponse),
495    (OpenUncommittedDiff, OpenUncommittedDiffResponse),
496    (GetSupermavenApiKey, GetSupermavenApiKeyResponse),
497    (GetTypeDefinition, GetTypeDefinitionResponse),
498    (LinkedEditingRange, LinkedEditingRangeResponse),
499    (ListRemoteDirectory, ListRemoteDirectoryResponse),
500    (GetUsers, UsersResponse),
501    (IncomingCall, Ack),
502    (InlayHints, InlayHintsResponse),
503    (InviteChannelMember, Ack),
504    (JoinChannel, JoinRoomResponse),
505    (JoinChannelBuffer, JoinChannelBufferResponse),
506    (JoinChannelChat, JoinChannelChatResponse),
507    (JoinProject, JoinProjectResponse),
508    (JoinRoom, JoinRoomResponse),
509    (LeaveChannelBuffer, Ack),
510    (LeaveRoom, Ack),
511    (MarkNotificationRead, Ack),
512    (MoveChannel, Ack),
513    (OnTypeFormatting, OnTypeFormattingResponse),
514    (OpenBufferById, OpenBufferResponse),
515    (OpenBufferByPath, OpenBufferResponse),
516    (OpenBufferForSymbol, OpenBufferForSymbolResponse),
517    (OpenCommitMessageBuffer, OpenBufferResponse),
518    (OpenNewBuffer, OpenBufferResponse),
519    (PerformRename, PerformRenameResponse),
520    (Ping, Ack),
521    (PrepareRename, PrepareRenameResponse),
522    (CountLanguageModelTokens, CountLanguageModelTokensResponse),
523    (RefreshInlayHints, Ack),
524    (RejoinChannelBuffers, RejoinChannelBuffersResponse),
525    (RejoinRoom, RejoinRoomResponse),
526    (ReloadBuffers, ReloadBuffersResponse),
527    (RemoveChannelMember, Ack),
528    (RemoveChannelMessage, Ack),
529    (UpdateChannelMessage, Ack),
530    (RemoveContact, Ack),
531    (RenameChannel, RenameChannelResponse),
532    (RenameProjectEntry, ProjectEntryResponse),
533    (RequestContact, Ack),
534    (
535        ResolveCompletionDocumentation,
536        ResolveCompletionDocumentationResponse
537    ),
538    (ResolveInlayHint, ResolveInlayHintResponse),
539    (RespondToChannelInvite, Ack),
540    (RespondToContactRequest, Ack),
541    (SaveBuffer, BufferSaved),
542    (Stage, Ack),
543    (FindSearchCandidates, FindSearchCandidatesResponse),
544    (SendChannelMessage, SendChannelMessageResponse),
545    (SetChannelMemberRole, Ack),
546    (SetChannelVisibility, Ack),
547    (ShareProject, ShareProjectResponse),
548    (SynchronizeBuffers, SynchronizeBuffersResponse),
549    (TaskContextForLocation, TaskContext),
550    (Test, Test),
551    (Unstage, Ack),
552    (UpdateBuffer, Ack),
553    (UpdateParticipantLocation, Ack),
554    (UpdateProject, Ack),
555    (UpdateWorktree, Ack),
556    (LspExtExpandMacro, LspExtExpandMacroResponse),
557    (LspExtOpenDocs, LspExtOpenDocsResponse),
558    (SetRoomParticipantRole, Ack),
559    (BlameBuffer, BlameBufferResponse),
560    (RejoinRemoteProjects, RejoinRemoteProjectsResponse),
561    (MultiLspQuery, MultiLspQueryResponse),
562    (RestartLanguageServers, Ack),
563    (OpenContext, OpenContextResponse),
564    (CreateContext, CreateContextResponse),
565    (SynchronizeContexts, SynchronizeContextsResponse),
566    (LspExtSwitchSourceHeader, LspExtSwitchSourceHeaderResponse),
567    (AddWorktree, AddWorktreeResponse),
568    (ShutdownRemoteServer, Ack),
569    (RemoveWorktree, Ack),
570    (OpenServerSettings, OpenBufferResponse),
571    (GetPermalinkToLine, GetPermalinkToLineResponse),
572    (FlushBufferedMessages, Ack),
573    (LanguageServerPromptRequest, LanguageServerPromptResponse),
574    (GitBranches, GitBranchesResponse),
575    (UpdateGitBranch, Ack),
576    (ListToolchains, ListToolchainsResponse),
577    (ActivateToolchain, Ack),
578    (ActiveToolchain, ActiveToolchainResponse),
579    (GetPathMetadata, GetPathMetadataResponse),
580    (GetPanicFiles, GetPanicFilesResponse),
581    (CancelLanguageServerWork, Ack),
582    (SyncExtensions, SyncExtensionsResponse),
583    (InstallExtension, Ack),
584    (RegisterBufferWithLanguageServers, Ack),
585    (GitShow, GitCommitDetails),
586    (GitReset, Ack),
587    (GitCheckoutFiles, Ack),
588    (SetIndexText, Ack),
589    (Push, Ack),
590    (Fetch, Ack),
591    (GetRemotes, GetRemotesResponse),
592    (Pull, Ack),
593);
594
595entity_messages!(
596    {project_id, ShareProject},
597    AddProjectCollaborator,
598    AddWorktree,
599    ApplyCodeAction,
600    ApplyCompletionAdditionalEdits,
601    BlameBuffer,
602    BufferReloaded,
603    BufferSaved,
604    CloseBuffer,
605    Commit,
606    CopyProjectEntry,
607    CreateBufferForPeer,
608    CreateProjectEntry,
609    DeleteProjectEntry,
610    ExpandProjectEntry,
611    ExpandAllForProjectEntry,
612    FindSearchCandidates,
613    FormatBuffers,
614    GetCodeActions,
615    GetCompletions,
616    GetDefinition,
617    GetDeclaration,
618    GetImplementation,
619    GetDocumentHighlights,
620    GetHover,
621    GetProjectSymbols,
622    GetReferences,
623    GetSignatureHelp,
624    OpenUnstagedDiff,
625    OpenUncommittedDiff,
626    GetTypeDefinition,
627    InlayHints,
628    JoinProject,
629    LeaveProject,
630    LinkedEditingRange,
631    MultiLspQuery,
632    RestartLanguageServers,
633    OnTypeFormatting,
634    OpenNewBuffer,
635    OpenBufferById,
636    OpenBufferByPath,
637    OpenBufferForSymbol,
638    OpenCommitMessageBuffer,
639    PerformRename,
640    PrepareRename,
641    RefreshInlayHints,
642    ReloadBuffers,
643    RemoveProjectCollaborator,
644    RenameProjectEntry,
645    ResolveCompletionDocumentation,
646    ResolveInlayHint,
647    SaveBuffer,
648    Stage,
649    StartLanguageServer,
650    SynchronizeBuffers,
651    TaskContextForLocation,
652    UnshareProject,
653    Unstage,
654    UpdateBuffer,
655    UpdateBufferFile,
656    UpdateDiagnosticSummary,
657    UpdateDiffBases,
658    UpdateLanguageServer,
659    UpdateProject,
660    UpdateProjectCollaborator,
661    UpdateWorktree,
662    UpdateWorktreeSettings,
663    LspExtExpandMacro,
664    LspExtOpenDocs,
665    AdvertiseContexts,
666    OpenContext,
667    CreateContext,
668    UpdateContext,
669    SynchronizeContexts,
670    LspExtSwitchSourceHeader,
671    LanguageServerLog,
672    Toast,
673    HideToast,
674    OpenServerSettings,
675    GetPermalinkToLine,
676    LanguageServerPromptRequest,
677    GitBranches,
678    UpdateGitBranch,
679    ListToolchains,
680    ActivateToolchain,
681    ActiveToolchain,
682    GetPathMetadata,
683    CancelLanguageServerWork,
684    RegisterBufferWithLanguageServers,
685    GitShow,
686    GitReset,
687    GitCheckoutFiles,
688    SetIndexText,
689    Push,
690    Fetch,
691    GetRemotes,
692    Pull,
693);
694
695entity_messages!(
696    {channel_id, Channel},
697    ChannelMessageSent,
698    ChannelMessageUpdate,
699    RemoveChannelMessage,
700    UpdateChannelMessage,
701    UpdateChannelBuffer,
702    UpdateChannelBufferCollaborators,
703);
704
705impl From<Timestamp> for SystemTime {
706    fn from(val: Timestamp) -> Self {
707        UNIX_EPOCH
708            .checked_add(Duration::new(val.seconds, val.nanos))
709            .unwrap()
710    }
711}
712
713impl From<SystemTime> for Timestamp {
714    fn from(time: SystemTime) -> Self {
715        let duration = time.duration_since(UNIX_EPOCH).unwrap();
716        Self {
717            seconds: duration.as_secs(),
718            nanos: duration.subsec_nanos(),
719        }
720    }
721}
722
723impl From<u128> for Nonce {
724    fn from(nonce: u128) -> Self {
725        let upper_half = (nonce >> 64) as u64;
726        let lower_half = nonce as u64;
727        Self {
728            upper_half,
729            lower_half,
730        }
731    }
732}
733
734impl From<Nonce> for u128 {
735    fn from(nonce: Nonce) -> Self {
736        let upper_half = (nonce.upper_half as u128) << 64;
737        let lower_half = nonce.lower_half as u128;
738        upper_half | lower_half
739    }
740}
741
742#[cfg(any(test, feature = "test-support"))]
743pub const MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE: usize = 2;
744#[cfg(not(any(test, feature = "test-support")))]
745pub const MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE: usize = 256;
746
747pub fn split_worktree_update(mut message: UpdateWorktree) -> impl Iterator<Item = UpdateWorktree> {
748    let mut done = false;
749
750    iter::from_fn(move || {
751        if done {
752            return None;
753        }
754
755        let updated_entries_chunk_size = cmp::min(
756            message.updated_entries.len(),
757            MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE,
758        );
759        let updated_entries: Vec<_> = message
760            .updated_entries
761            .drain(..updated_entries_chunk_size)
762            .collect();
763
764        let removed_entries_chunk_size = cmp::min(
765            message.removed_entries.len(),
766            MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE,
767        );
768        let removed_entries = message
769            .removed_entries
770            .drain(..removed_entries_chunk_size)
771            .collect();
772
773        let mut updated_repositories = Vec::new();
774        let mut limit = MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE;
775        while let Some(repo) = message.updated_repositories.first_mut() {
776            let updated_statuses_limit = cmp::min(repo.updated_statuses.len(), limit);
777            let removed_statuses_limit = cmp::min(repo.removed_statuses.len(), limit);
778
779            updated_repositories.push(RepositoryEntry {
780                work_directory_id: repo.work_directory_id,
781                branch: repo.branch.clone(),
782                branch_summary: repo.branch_summary.clone(),
783                updated_statuses: repo
784                    .updated_statuses
785                    .drain(..updated_statuses_limit)
786                    .collect(),
787                removed_statuses: repo
788                    .removed_statuses
789                    .drain(..removed_statuses_limit)
790                    .collect(),
791                current_merge_conflicts: repo.current_merge_conflicts.clone(),
792            });
793            if repo.removed_statuses.is_empty() && repo.updated_statuses.is_empty() {
794                message.updated_repositories.remove(0);
795            }
796            limit = limit.saturating_sub(removed_statuses_limit + updated_statuses_limit);
797            if limit == 0 {
798                break;
799            }
800        }
801
802        done = message.updated_entries.is_empty()
803            && message.removed_entries.is_empty()
804            && message.updated_repositories.is_empty();
805
806        let removed_repositories = if done {
807            mem::take(&mut message.removed_repositories)
808        } else {
809            Default::default()
810        };
811
812        Some(UpdateWorktree {
813            project_id: message.project_id,
814            worktree_id: message.worktree_id,
815            root_name: message.root_name.clone(),
816            abs_path: message.abs_path.clone(),
817            updated_entries,
818            removed_entries,
819            scan_id: message.scan_id,
820            is_last_update: done && message.is_last_update,
821            updated_repositories,
822            removed_repositories,
823        })
824    })
825}
826
827#[cfg(test)]
828mod tests {
829    use super::*;
830
831    #[test]
832    fn test_converting_peer_id_from_and_to_u64() {
833        let peer_id = PeerId {
834            owner_id: 10,
835            id: 3,
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: 3,
841        };
842        assert_eq!(PeerId::from_u64(peer_id.as_u64()), peer_id);
843        let peer_id = PeerId {
844            owner_id: 10,
845            id: u32::MAX,
846        };
847        assert_eq!(PeerId::from_u64(peer_id.as_u64()), peer_id);
848        let peer_id = PeerId {
849            owner_id: u32::MAX,
850            id: u32::MAX,
851        };
852        assert_eq!(PeerId::from_u64(peer_id.as_u64()), peer_id);
853    }
854
855    #[test]
856    #[cfg(target_os = "windows")]
857    fn test_proto() {
858        fn generate_proto_path(path: PathBuf) -> PathBuf {
859            let proto = path.to_proto();
860            PathBuf::from_proto(proto)
861        }
862
863        let path = PathBuf::from("C:\\foo\\bar");
864        assert_eq!(path, generate_proto_path(path.clone()));
865
866        let path = PathBuf::from("C:/foo/bar/");
867        assert_eq!(path, generate_proto_path(path.clone()));
868
869        let path = PathBuf::from("C:/foo\\bar\\");
870        assert_eq!(path, generate_proto_path(path.clone()));
871    }
872}