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
 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);
444
445request_messages!(
446    (AcceptTermsOfService, AcceptTermsOfServiceResponse),
447    (ApplyCodeAction, ApplyCodeActionResponse),
448    (
449        ApplyCompletionAdditionalEdits,
450        ApplyCompletionAdditionalEditsResponse
451    ),
452    (Call, Ack),
453    (CancelCall, Ack),
454    (Commit, Ack),
455    (CopyProjectEntry, ProjectEntryResponse),
456    (ComputeEmbeddings, ComputeEmbeddingsResponse),
457    (CreateChannel, CreateChannelResponse),
458    (CreateProjectEntry, ProjectEntryResponse),
459    (CreateRoom, CreateRoomResponse),
460    (DeclineCall, Ack),
461    (DeleteChannel, Ack),
462    (DeleteProjectEntry, ProjectEntryResponse),
463    (ExpandProjectEntry, ExpandProjectEntryResponse),
464    (ExpandAllForProjectEntry, ExpandAllForProjectEntryResponse),
465    (Follow, FollowResponse),
466    (FormatBuffers, FormatBuffersResponse),
467    (FuzzySearchUsers, UsersResponse),
468    (GetCachedEmbeddings, GetCachedEmbeddingsResponse),
469    (GetChannelMembers, GetChannelMembersResponse),
470    (GetChannelMessages, GetChannelMessagesResponse),
471    (GetChannelMessagesById, GetChannelMessagesResponse),
472    (GetCodeActions, GetCodeActionsResponse),
473    (GetCompletions, GetCompletionsResponse),
474    (GetDefinition, GetDefinitionResponse),
475    (GetDeclaration, GetDeclarationResponse),
476    (GetImplementation, GetImplementationResponse),
477    (GetDocumentHighlights, GetDocumentHighlightsResponse),
478    (GetHover, GetHoverResponse),
479    (GetLlmToken, GetLlmTokenResponse),
480    (GetNotifications, GetNotificationsResponse),
481    (GetPrivateUserInfo, GetPrivateUserInfoResponse),
482    (GetProjectSymbols, GetProjectSymbolsResponse),
483    (GetReferences, GetReferencesResponse),
484    (GetSignatureHelp, GetSignatureHelpResponse),
485    (OpenUnstagedDiff, OpenUnstagedDiffResponse),
486    (OpenUncommittedDiff, OpenUncommittedDiffResponse),
487    (GetSupermavenApiKey, GetSupermavenApiKeyResponse),
488    (GetTypeDefinition, GetTypeDefinitionResponse),
489    (LinkedEditingRange, LinkedEditingRangeResponse),
490    (ListRemoteDirectory, ListRemoteDirectoryResponse),
491    (GetUsers, UsersResponse),
492    (IncomingCall, Ack),
493    (InlayHints, InlayHintsResponse),
494    (InviteChannelMember, Ack),
495    (JoinChannel, JoinRoomResponse),
496    (JoinChannelBuffer, JoinChannelBufferResponse),
497    (JoinChannelChat, JoinChannelChatResponse),
498    (JoinProject, JoinProjectResponse),
499    (JoinRoom, JoinRoomResponse),
500    (LeaveChannelBuffer, Ack),
501    (LeaveRoom, Ack),
502    (MarkNotificationRead, Ack),
503    (MoveChannel, Ack),
504    (OnTypeFormatting, OnTypeFormattingResponse),
505    (OpenBufferById, OpenBufferResponse),
506    (OpenBufferByPath, OpenBufferResponse),
507    (OpenBufferForSymbol, OpenBufferForSymbolResponse),
508    (OpenCommitMessageBuffer, OpenBufferResponse),
509    (OpenNewBuffer, OpenBufferResponse),
510    (PerformRename, PerformRenameResponse),
511    (Ping, Ack),
512    (PrepareRename, PrepareRenameResponse),
513    (CountLanguageModelTokens, CountLanguageModelTokensResponse),
514    (RefreshInlayHints, Ack),
515    (RejoinChannelBuffers, RejoinChannelBuffersResponse),
516    (RejoinRoom, RejoinRoomResponse),
517    (ReloadBuffers, ReloadBuffersResponse),
518    (RemoveChannelMember, Ack),
519    (RemoveChannelMessage, Ack),
520    (UpdateChannelMessage, Ack),
521    (RemoveContact, Ack),
522    (RenameChannel, RenameChannelResponse),
523    (RenameProjectEntry, ProjectEntryResponse),
524    (RequestContact, Ack),
525    (
526        ResolveCompletionDocumentation,
527        ResolveCompletionDocumentationResponse
528    ),
529    (ResolveInlayHint, ResolveInlayHintResponse),
530    (RespondToChannelInvite, Ack),
531    (RespondToContactRequest, Ack),
532    (SaveBuffer, BufferSaved),
533    (Stage, Ack),
534    (FindSearchCandidates, FindSearchCandidatesResponse),
535    (SendChannelMessage, SendChannelMessageResponse),
536    (SetChannelMemberRole, Ack),
537    (SetChannelVisibility, Ack),
538    (ShareProject, ShareProjectResponse),
539    (SynchronizeBuffers, SynchronizeBuffersResponse),
540    (TaskContextForLocation, TaskContext),
541    (Test, Test),
542    (Unstage, Ack),
543    (UpdateBuffer, Ack),
544    (UpdateParticipantLocation, Ack),
545    (UpdateProject, Ack),
546    (UpdateWorktree, Ack),
547    (LspExtExpandMacro, LspExtExpandMacroResponse),
548    (LspExtOpenDocs, LspExtOpenDocsResponse),
549    (SetRoomParticipantRole, Ack),
550    (BlameBuffer, BlameBufferResponse),
551    (RejoinRemoteProjects, RejoinRemoteProjectsResponse),
552    (MultiLspQuery, MultiLspQueryResponse),
553    (RestartLanguageServers, Ack),
554    (OpenContext, OpenContextResponse),
555    (CreateContext, CreateContextResponse),
556    (SynchronizeContexts, SynchronizeContextsResponse),
557    (LspExtSwitchSourceHeader, LspExtSwitchSourceHeaderResponse),
558    (AddWorktree, AddWorktreeResponse),
559    (ShutdownRemoteServer, Ack),
560    (RemoveWorktree, Ack),
561    (OpenServerSettings, OpenBufferResponse),
562    (GetPermalinkToLine, GetPermalinkToLineResponse),
563    (FlushBufferedMessages, Ack),
564    (LanguageServerPromptRequest, LanguageServerPromptResponse),
565    (GitBranches, GitBranchesResponse),
566    (UpdateGitBranch, Ack),
567    (ListToolchains, ListToolchainsResponse),
568    (ActivateToolchain, Ack),
569    (ActiveToolchain, ActiveToolchainResponse),
570    (GetPathMetadata, GetPathMetadataResponse),
571    (GetPanicFiles, GetPanicFilesResponse),
572    (CancelLanguageServerWork, Ack),
573    (SyncExtensions, SyncExtensionsResponse),
574    (InstallExtension, Ack),
575    (RegisterBufferWithLanguageServers, Ack),
576);
577
578entity_messages!(
579    {project_id, ShareProject},
580    AddProjectCollaborator,
581    AddWorktree,
582    ApplyCodeAction,
583    ApplyCompletionAdditionalEdits,
584    BlameBuffer,
585    BufferReloaded,
586    BufferSaved,
587    CloseBuffer,
588    Commit,
589    CopyProjectEntry,
590    CreateBufferForPeer,
591    CreateProjectEntry,
592    DeleteProjectEntry,
593    ExpandProjectEntry,
594    ExpandAllForProjectEntry,
595    FindSearchCandidates,
596    FormatBuffers,
597    GetCodeActions,
598    GetCompletions,
599    GetDefinition,
600    GetDeclaration,
601    GetImplementation,
602    GetDocumentHighlights,
603    GetHover,
604    GetProjectSymbols,
605    GetReferences,
606    GetSignatureHelp,
607    OpenUnstagedDiff,
608    OpenUncommittedDiff,
609    GetTypeDefinition,
610    InlayHints,
611    JoinProject,
612    LeaveProject,
613    LinkedEditingRange,
614    MultiLspQuery,
615    RestartLanguageServers,
616    OnTypeFormatting,
617    OpenNewBuffer,
618    OpenBufferById,
619    OpenBufferByPath,
620    OpenBufferForSymbol,
621    OpenCommitMessageBuffer,
622    PerformRename,
623    PrepareRename,
624    RefreshInlayHints,
625    ReloadBuffers,
626    RemoveProjectCollaborator,
627    RenameProjectEntry,
628    ResolveCompletionDocumentation,
629    ResolveInlayHint,
630    SaveBuffer,
631    Stage,
632    StartLanguageServer,
633    SynchronizeBuffers,
634    TaskContextForLocation,
635    UnshareProject,
636    Unstage,
637    UpdateBuffer,
638    UpdateBufferFile,
639    UpdateDiagnosticSummary,
640    UpdateDiffBases,
641    UpdateLanguageServer,
642    UpdateProject,
643    UpdateProjectCollaborator,
644    UpdateWorktree,
645    UpdateWorktreeSettings,
646    LspExtExpandMacro,
647    LspExtOpenDocs,
648    AdvertiseContexts,
649    OpenContext,
650    CreateContext,
651    UpdateContext,
652    SynchronizeContexts,
653    LspExtSwitchSourceHeader,
654    LanguageServerLog,
655    Toast,
656    HideToast,
657    OpenServerSettings,
658    GetPermalinkToLine,
659    LanguageServerPromptRequest,
660    GitBranches,
661    UpdateGitBranch,
662    ListToolchains,
663    ActivateToolchain,
664    ActiveToolchain,
665    GetPathMetadata,
666    CancelLanguageServerWork,
667    RegisterBufferWithLanguageServers,
668);
669
670entity_messages!(
671    {channel_id, Channel},
672    ChannelMessageSent,
673    ChannelMessageUpdate,
674    RemoveChannelMessage,
675    UpdateChannelMessage,
676    UpdateChannelBuffer,
677    UpdateChannelBufferCollaborators,
678);
679
680impl From<Timestamp> for SystemTime {
681    fn from(val: Timestamp) -> Self {
682        UNIX_EPOCH
683            .checked_add(Duration::new(val.seconds, val.nanos))
684            .unwrap()
685    }
686}
687
688impl From<SystemTime> for Timestamp {
689    fn from(time: SystemTime) -> Self {
690        let duration = time.duration_since(UNIX_EPOCH).unwrap();
691        Self {
692            seconds: duration.as_secs(),
693            nanos: duration.subsec_nanos(),
694        }
695    }
696}
697
698impl From<u128> for Nonce {
699    fn from(nonce: u128) -> Self {
700        let upper_half = (nonce >> 64) as u64;
701        let lower_half = nonce as u64;
702        Self {
703            upper_half,
704            lower_half,
705        }
706    }
707}
708
709impl From<Nonce> for u128 {
710    fn from(nonce: Nonce) -> Self {
711        let upper_half = (nonce.upper_half as u128) << 64;
712        let lower_half = nonce.lower_half as u128;
713        upper_half | lower_half
714    }
715}
716
717#[cfg(any(test, feature = "test-support"))]
718pub const MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE: usize = 2;
719#[cfg(not(any(test, feature = "test-support")))]
720pub const MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE: usize = 256;
721
722pub fn split_worktree_update(mut message: UpdateWorktree) -> impl Iterator<Item = UpdateWorktree> {
723    let mut done_files = false;
724
725    let mut repository_map = message
726        .updated_repositories
727        .into_iter()
728        .map(|repo| (repo.work_directory_id, repo))
729        .collect::<HashMap<_, _>>();
730
731    iter::from_fn(move || {
732        if done_files {
733            return None;
734        }
735
736        let updated_entries_chunk_size = cmp::min(
737            message.updated_entries.len(),
738            MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE,
739        );
740        let updated_entries: Vec<_> = message
741            .updated_entries
742            .drain(..updated_entries_chunk_size)
743            .collect();
744
745        let removed_entries_chunk_size = cmp::min(
746            message.removed_entries.len(),
747            MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE,
748        );
749        let removed_entries = message
750            .removed_entries
751            .drain(..removed_entries_chunk_size)
752            .collect();
753
754        done_files = message.updated_entries.is_empty() && message.removed_entries.is_empty();
755
756        let mut updated_repositories = Vec::new();
757
758        if !repository_map.is_empty() {
759            for entry in &updated_entries {
760                if let Some(repo) = repository_map.remove(&entry.id) {
761                    updated_repositories.push(repo);
762                }
763            }
764        }
765
766        let removed_repositories = if done_files {
767            mem::take(&mut message.removed_repositories)
768        } else {
769            Default::default()
770        };
771
772        if done_files {
773            updated_repositories.extend(mem::take(&mut repository_map).into_values());
774        }
775
776        Some(UpdateWorktree {
777            project_id: message.project_id,
778            worktree_id: message.worktree_id,
779            root_name: message.root_name.clone(),
780            abs_path: message.abs_path.clone(),
781            updated_entries,
782            removed_entries,
783            scan_id: message.scan_id,
784            is_last_update: done_files && message.is_last_update,
785            updated_repositories,
786            removed_repositories,
787        })
788    })
789}
790
791#[cfg(test)]
792mod tests {
793    use super::*;
794
795    #[test]
796    fn test_converting_peer_id_from_and_to_u64() {
797        let peer_id = PeerId {
798            owner_id: 10,
799            id: 3,
800        };
801        assert_eq!(PeerId::from_u64(peer_id.as_u64()), peer_id);
802        let peer_id = PeerId {
803            owner_id: u32::MAX,
804            id: 3,
805        };
806        assert_eq!(PeerId::from_u64(peer_id.as_u64()), peer_id);
807        let peer_id = PeerId {
808            owner_id: 10,
809            id: u32::MAX,
810        };
811        assert_eq!(PeerId::from_u64(peer_id.as_u64()), peer_id);
812        let peer_id = PeerId {
813            owner_id: u32::MAX,
814            id: u32::MAX,
815        };
816        assert_eq!(PeerId::from_u64(peer_id.as_u64()), peer_id);
817    }
818
819    #[test]
820    #[cfg(target_os = "windows")]
821    fn test_proto() {
822        fn generate_proto_path(path: PathBuf) -> PathBuf {
823            let proto = path.to_proto();
824            PathBuf::from_proto(proto)
825        }
826
827        let path = PathBuf::from("C:\\foo\\bar");
828        assert_eq!(path, generate_proto_path(path.clone()));
829
830        let path = PathBuf::from("C:/foo/bar/");
831        assert_eq!(path, generate_proto_path(path.clone()));
832
833        let path = PathBuf::from("C:/foo\\bar\\");
834        assert_eq!(path, generate_proto_path(path.clone()));
835    }
836}