Debian Codegraph @

src/base/castlemessaging.pas

raw
1 {
2 Copyright 2015-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Message system to communicate with services implemented in other languages
17 (in Java on Android, or Objective-C on iOS)
18 (TMessaging class). }
19 unit CastleMessaging;
20
21 {$I castleconf.inc}
22
23 interface
24
25 uses
26 {$ifdef ANDROID} JNI, SyncObjs, {$endif}
27 {$ifdef CASTLE_IOS} CTypes, {$endif}
28 Generics.Collections, Classes,
29 CastleStringUtils, CastleTimeUtils;
30
31 type
32 { Called by TMessaging when a new message from service is received.
33
34 Returns if the message was handled (this does @bold(not) block
35 the message from being passed to other callbacks, it only means
36 we will not report a warning about unhandled message).
37
38 ReceivedStream may be @nil if service didn't provide any binary data stream.
39 }
40 TMessageReceivedEvent = function (const Received: TCastleStringList;
41 const ReceivedStream: TMemoryStream): Boolean of object;
42
43 { Used by TMessaging to manage a list of listeners. }
44 TMessageReceivedEventList = class({$ifdef FPC}specialize{$endif} TList<TMessageReceivedEvent>)
45 public
46 procedure ExecuteAll(const Received: TCastleStringList; const ReceivedStream: TMemoryStream);
47 end;
48
49 { Message system to communicate between native code (Pascal) and other languages
50 (Java on Android, Objective-C on iOS) that possibly run in other thread.
51 Use through auto-created @link(Messaging) singleton.
52 On platforms other than Android / iOS, it simply does nothing
53 --- messsages are not send anywhere.
54
55 To make this work, on Android you need to declare your Android project type
56 as "integrated" (this is actually the default now).
57 See https://castle-engine.io/android-Services .
58 For iOS it is always enabled.
59
60 All the communication is asynchronous on all platforms -- Pascal code sends a message,
61 and any answers will come asynchronously later. This means that e.g.
62 @link(TGameService.RequestSignedIn) will never call
63 @link(TGameService.OnStatusChanged) right inside,
64 the call to @link(TGameService.OnStatusChanged) will always happen at a later time.
65
66 This is used automatically by various engine classes like
67 @link(TGameService), @link(TAds), @link(TAnalytics), @link(TInAppPurchases). }
68 TMessaging = class
69 private
70 {$ifdef ANDROID}
71 JavaCommunicationCS: TCriticalSection;
72 FromPascal: TCastleStringList;
73 {$endif}
74
75 {$ifdef CASTLE_IOS}
76 type
77 TReceiveMessageFromPascalCallback = procedure (Message: PCChar); cdecl;
78 class var
79 FReceiveMessageFromPascalCallback: TReceiveMessageFromPascalCallback;
80 {$endif}
81
82 var
83 ToPascal: TCastleStringList;
84 FOnReceive: TMessageReceivedEventList;
85 FLog: boolean;
86 { Called constantly to empty the ToPascal list. }
87 procedure Update(Sender: TObject);
88 public
89 constructor Create;
90 destructor Destroy; override;
91
92 { Send a message to a service (implemented in other language,
93 like Java on Android or Objective-C on iOS). }
94 procedure Send(const Strings: array of string);
95
96 { Callbacks called when new message from service is received. }
97 property OnReceive: TMessageReceivedEventList read FOnReceive;
98
99 { Log each message send/received from/to service.
100 Note that this is sometimes quite verbose, and it also allows cheaters
101 to easier debug what happens in your game (e.g. how to fake getting
102 some achievement), so in general don't leave it "on" in production. }
103 property Log: boolean read FLog write FLog default false;
104
105 { Convert boolean to 'true' or 'false' string, which will be understood correctly
106 by the service receiving the messages. }
107 class function BoolToStr(const Value: boolean): string;
108
109 { Convert float time (in seconds) to integer miliseconds, which are understood correctly
110 by the service receiving the messages. }
111 class function TimeToStr(const Value: TFloatTime): string;
112
113 { Convert string to a boolean, assuming the string was send by the external service.
114 The counterpart of this in Android is ServiceAbstract.booleanToString . }
115 class function MessageToBoolean(const Value: String): Boolean;
116 end;
117
118 {$ifdef ANDROID}
119 { Export this function from your Android library. }
120 function Java_io_castleengine_MainActivity_jniMessage(
121 Env: PJNIEnv; This: jobject;
122 MessageToPascal: jstring;
123 MessageToPascalStream: jbyteArray): jstring; cdecl;
124 {$endif}
125
126 {$ifdef CASTLE_IOS}
127 procedure CGEApp_SetReceiveMessageFromPascalCallback(
128 ACallback: TMessaging.TReceiveMessageFromPascalCallback); cdecl;
129 procedure CGEApp_SendMessageToPascal(Message: PCChar); cdecl;
130 {$endif}
131
132 { Auto-created single instance of @link(TMessaging) to communicate
133 between native code (Pascal) and other languages (Java on Android, Objective-C on iOS). }
134 function Messaging: TMessaging;
135
136 implementation
137
138 uses SysUtils,
139 CastleUtils, CastleLog, CastleApplicationProperties;
140
141 { TMessageReceivedEventList -------------------------------------------------- }
142
143 procedure TMessageReceivedEventList.ExecuteAll(const Received: TCastleStringList;
144 const ReceivedStream: TMemoryStream);
145 var
146 I: Integer;
147 EventResult, Handled: boolean;
148 begin
149 Handled := false;
150
151 // The permission-xxx messages do not have to be handled by anything.
152 if (Received.Count > 0) and
153 ( (Received[0] = 'permission-granted') or
154 (Received[0] = 'permission-cancelled') ) then
155 Handled := true;
156
157 for I := 0 to Count - 1 do
158 begin
159 { Use EventResult to workaround FPC 3.1.1 bug (reproducible
160 with FPC SVN revision 35460 (from 2016-02-20) on Linux x86_64).
161 The bug has since been fixed http://bugs.freepascal.org/view.php?id=31421 ,
162 so we may remove this workaround soon. }
163 EventResult := Items[I](Received, ReceivedStream);
164 Handled := EventResult or Handled;
165 end;
166 if not Handled then
167 WritelnWarning('Messaging', 'Unhandled message from service:' + NL + Received.Text);
168 end;
169
170 { TMessaging ----------------------------------------------------------------- }
171
172 constructor TMessaging.Create;
173 begin
174 inherited;
175 FOnReceive := TMessageReceivedEventList.Create;
176 ToPascal := TCastleStringList.Create;
177
178 {$ifdef ANDROID}
179 JavaCommunicationCS := TCriticalSection.Create;
180 FromPascal := TCastleStringList.Create;
181 {$endif ANDROID}
182
183 { Only register the Update on platforms where CastleMessaging is actually used. }
184 {$if defined(ANDROID) or defined(CASTLE_IOS)}
185 ApplicationProperties.OnUpdate.Add({$ifdef FPC}@{$endif} Update);
186 {$endif}
187 end;
188
189 destructor TMessaging.Destroy;
190 begin
191 if ApplicationProperties(false) <> nil then
192 ApplicationProperties(false).OnUpdate.Remove({$ifdef FPC}@{$endif} Update);
193 FreeAndNil(ToPascal);
194 FreeAndNil(FOnReceive);
195
196 {$ifdef ANDROID}
197 FreeAndNil(JavaCommunicationCS);
198 FreeAndNil(FromPascal);
199 {$endif ANDROID}
200
201 inherited;
202 end;
203
204 const
205 { This is a nice separator, as it has really low chance of occuring in non-binary data.
206 - It's also not 0, so it will not be confused with "end of string" (Pascal is invulnerable
207 to this, and can have #0 in the middle of AnsiString freely
208 but I'm not so sure about Java or Objective-C NSString).
209 - It's also within ASCII range, so it will not occur within any UTF-8 multibyte sequence
210 (UTF-8 treats specially only stuff > 128, and you can search for ASCII substrings disregaring
211 the UTF-8 multibyte stuff, as far as I know). }
212 MessageDelimiter = #1;
213
214 procedure TMessaging.Send(const Strings: array of string);
215
216 procedure SendStr(const Message: string);
217 begin
218 { secure in case this is called from state Finish when things are finalized }
219 if Self = nil then Exit;
220
221 if Log then
222 WritelnLog('Messaging', 'Pascal code sends a message to service: ' + SReadableForm(Message));
223
224 {$ifdef ANDROID}
225 JavaCommunicationCS.Acquire;
226 try
227 FromPascal.Add(Message);
228 finally JavaCommunicationCS.Release end;
229 {$endif ANDROID}
230
231 {$ifdef CASTLE_IOS}
232 if Assigned(FReceiveMessageFromPascalCallback) then
233 FReceiveMessageFromPascalCallback(PCChar(Message))
234 else
235 WritelnWarning('Messaging', 'Message cannot be delivered, iOS application not finished loading yet');
236 {$endif CASTLE_IOS}
237 end;
238
239 begin
240 if High(Strings) = -1 then Exit; // exit in case of empty list
241 SendStr(GlueStrings(Strings, MessageDelimiter));
242 end;
243
244 procedure TMessaging.Update(Sender: TObject);
245
246 { Handle message using Pascal logic.
247 MessageStream may be @nil if service didn't provide any binary data stream. }
248 procedure ReceiveStr(const Message: String; const MessageStream: TMemoryStream);
249 var
250 MessageAsList: TCastleStringList;
251 begin
252 if Log then
253 WritelnLog('Messaging', 'Pascal code received a message from service: ' + SReadableForm(Message));
254 if Message = '' then
255 WritelnWarning('Messaging', 'Pascal code received an empty message');
256
257 MessageAsList := CastleStringUtils.SplitString(Message, MessageDelimiter);
258 try
259 OnReceive.ExecuteAll(MessageAsList, MessageStream);
260 finally FreeAndNil(MessageAsList) end;
261 end;
262
263 function GetNextMessageToPascal(out Received: String; out ReceivedStream: TMemoryStream): Boolean;
264 begin
265 {$ifdef ANDROID}
266 JavaCommunicationCS.Acquire;
267 try
268 {$endif ANDROID}
269
270 Result := ToPascal.Count <> 0;
271 if Result then
272 begin
273 Received := ToPascal[0];
274 ReceivedStream := ToPascal.Objects[0] as TMemoryStream;
275 ToPascal.Delete(0);
276 end;
277
278 {$ifdef ANDROID}
279 finally JavaCommunicationCS.Release end;
280 {$endif ANDROID}
281 end;
282
283 var
284 Received: String;
285 ReceivedStream: TMemoryStream;
286 begin
287 while GetNextMessageToPascal(Received, ReceivedStream) do
288 begin
289 ReceiveStr(Received, ReceivedStream);
290 FreeAndNil(ReceivedStream);
291 end;
292 end;
293
294 class function TMessaging.BoolToStr(const Value: boolean): string;
295 begin
296 Result := Iff(Value, 'true', 'false');
297 end;
298
299 class function TMessaging.TimeToStr(const Value: TFloatTime): string;
300 begin
301 Result := IntToStr(Trunc(Value * 1000));
302 end;
303
304 class function TMessaging.MessageToBoolean(const Value: String): Boolean;
305 begin
306 if Value = 'true' then
307 Result := true
308 else
309 if Value = 'false' then
310 Result := false
311 else
312 raise EInternalError.CreateFmt('Invalid boolean value in message: %s', [Value]);
313 end;
314
315 { globals -------------------------------------------------------------------- }
316
317 var
318 FMessaging: TMessaging;
319 FinalizationDone: boolean;
320
321 procedure DoInitialization;
322 begin
323 if (not FinalizationDone) and (FMessaging = nil) then
324 FMessaging := TMessaging.Create;
325 end;
326
327 function Messaging: TMessaging;
328 begin
329 { in case you access Messaging before our unit "initialization" works
330 (for example, in case your unit "initiazalition" is executed first and
331 it does does some Messaging.Send), then initialize us now. }
332 DoInitialization;
333
334 Result := FMessaging;
335 end;
336
337 { iOS specific --------------------------------------------------------------- }
338
339 {$ifdef CASTLE_IOS}
340 procedure CGEApp_SetReceiveMessageFromPascalCallback(
341 ACallback: TMessaging.TReceiveMessageFromPascalCallback); cdecl;
342 begin
343 Messaging.FReceiveMessageFromPascalCallback := ACallback;
344 end;
345
346 procedure CGEApp_SendMessageToPascal(Message: PCChar); cdecl;
347 begin
348 { For consistent behavior with Android, do not receive and process messages synchronously. }
349 // Messaging.ReceiveStr(AnsiString(PChar(Message)));
350
351 Messaging.ToPascal.Add(AnsiString(PChar(Message)));
352 end;
353 {$endif CASTLE_IOS}
354
355 { Android specific ----------------------------------------------------------- }
356
357 {$ifdef ANDROID}
358 function Java_io_castleengine_MainActivity_jniMessage(
359 Env: PJNIEnv; This: jobject;
360 MessageToPascal: jstring;
361 MessageToPascalStream: jbyteArray): jstring; cdecl;
362
363 { Read Java byte[] into TMemoryStream. }
364 function GetBinaryDataStream(const BytesObject: jbyteArray): TMemoryStream;
365 var
366 Bytes: PJByte;
367 Dummy: JBoolean;
368 Len: JSize;
369 begin
370 { See https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/functions.html
371 about JNI functions meaning. }
372 Len := Env^^.GetArrayLength(Env, BytesObject);
373 Bytes := Env^^.GetByteArrayElements(Env, BytesObject, Dummy);
374 try
375 Result := TMemoryStream.Create;
376 if Len <> 0 then
377 Result.WriteBuffer(Bytes^, Len);
378 finally Env^^.ReleaseByteArrayElements(Env, BytesObject, Bytes, 0) end;
379 end;
380
381 var
382 MessageToPascalStr: PChar;
383 Dummy: JBoolean;
384 Stream: TObject;
385 begin
386 { As this may be called from different thread, secure from being called
387 in weird state. }
388 if (FMessaging <> nil) and
389 (FMessaging.JavaCommunicationCS <> nil) and
390 (FMessaging.FromPascal <> nil) and
391 (FMessaging.ToPascal <> nil) then
392 begin
393 FMessaging.JavaCommunicationCS.Acquire;
394 try
395 if FMessaging.FromPascal.Count <> 0 then
396 begin
397 Result := Env^^.NewStringUTF(Env, PChar(FMessaging.FromPascal[0]));
398 FMessaging.FromPascal.Delete(0);
399 end else
400 Result := Env^^.NewStringUTF(Env, nil);
401
402 if MessageToPascalStream <> nil then
403 Stream := GetBinaryDataStream(MessageToPascalStream)
404 else
405 Stream := nil;
406
407 if (MessageToPascal <> nil) and
408 (Env^^.GetStringUTFLength(Env, MessageToPascal) <> 0) then
409 begin
410 Dummy := 0;
411 MessageToPascalStr := Env^^.GetStringUTFChars(Env, MessageToPascal,
412 {$ifdef VER2} Dummy {$else} @Dummy {$endif});
413 try
414 FMessaging.ToPascal.AddObject(AnsiString(MessageToPascalStr), Stream); // will copy characters
415 finally Env^^.ReleaseStringUTFChars(Env, MessageToPascal, MessageToPascalStr) end;
416 end;
417 finally FMessaging.JavaCommunicationCS.Release end;
418 end;
419 end;
420 {$endif ANDROID}
421
422 initialization
423 DoInitialization;
424 finalization
425 FinalizationDone := true;
426 FreeAndNil(FMessaging);
427 end.