Debian Codegraph @

src/base/android/castleandroidnativeappglue.pas

raw
1 (*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 *)
17
18 unit CastleAndroidNativeAppGlue;
19
20 {$I castleconf.inc}
21
22 interface
23
24 uses
25 { Using CThreads is necessary, otherwise we cannot use FPC threads
26 (TThread.Create simply terminates the process).
27
28 And we really want to use FPC threads. Do not directly use non-FPC
29 threads, e.g. do not create thread using pthread_create like original
30 native_android_app_glue code from Google says.
31 Weird things can happen
32 if you use external threads (created by pthreads) without any FPC knowledge.
33 See http://wiki.freepascal.org/Multithreaded_Application_Tutorial#External_threads .
34 The symptoms are random segfaults, e.g. after checking MainWindow.Closed
35 the drawing_toy started making segfaults at fpc_popaddrstack is various
36 code places.
37
38 Using CThreads (that actually wraps pthread threads underneath) makes
39 code simple and stable.
40
41 CThreads *must* be the 1st unit on "uses" clause here,
42 and CastleAndroidNativeAppGlue *must* be the 1st unit on
43 "uses" clause of your Android library. }
44 CThreads,
45
46 ctypes,baseunix,unixtype,
47 CastleAndroidInternalConfiguration, CastleAndroidInternalLooper, CastleAndroidInternalLog,
48 CastleAndroidInternalInput, CastleAndroidInternalRect, CastleAndroidInternalNativeWindow,
49 CastleAndroidInternalNativeActivity;
50
51 (**
52 * The native activity interface provided by <android/native_activity.h>
53 * is based on a set of application-provided callbacks that will be called
54 * by the Activity's main thread when certain events occur.
55 *
56 * This means that each one of this callbacks _should_ _not_ block, or they
57 * risk having the system force-close the application. This programming
58 * model is direct, lightweight, but constraining.
59 *
60 * The 'threaded_native_app' static library is used to provide a different
61 * execution model where the application can implement its own main event
62 * loop in a different thread instead. Here's how it works:
63 *
64 * 1/ The application must provide a function named "android_main()" that
65 * will be called when the activity is created, in a new thread that is
66 * distinct from the activity's main thread.
67 *
68 * 2/ android_main() receives a pointer to a valid "android_app" structure
69 * that contains references to other important objects, e.g. the
70 * ANativeActivity obejct instance the application is running in.
71 *
72 * 3/ the "android_app" object holds an ALooper instance that already
73 * listens to two important things:
74 *
75 * - activity lifecycle events (e.g. "pause", "resume"). See APP_CMD_XXX
76 * declarations below.
77 *
78 * - input events coming from the AInputQueue attached to the activity.
79 *
80 * Each of these correspond to an ALooper identifier returned by
81 * ALooper_pollOnce with values of LOOPER_ID_MAIN and LOOPER_ID_INPUT,
82 * respectively.
83 *
84 * Your application can use the same ALooper to listen to additional
85 * file-descriptors. They can either be callback based, or with return
86 * identifiers starting with LOOPER_ID_USER.
87 *
88 * 4/ Whenever you receive a LOOPER_ID_MAIN or LOOPER_ID_INPUT event,
89 * the returned data will point to an android_poll_source structure. You
90 * can call the process() function on it, and fill in android_app->onAppCmd
91 * and android_app->onInputEvent to be called for your own processing
92 * of the event.
93 *
94 * Alternatively, you can call the low-level functions to read and process
95 * the data directly... look at the process_cmd() and process_input()
96 * implementations in the glue to see how to do this.
97 *
98 * See the sample named "native-activity" that comes with the NDK with a
99 * full usage example. Also look at the JavaDoc of NativeActivity.
100 *)
101
102 (**
103 * Data associated with an ALooper fd that will be returned as the "outData"
104 * when that source has data ready.
105 *)
106
107 type
108 Pandroid_poll_source = ^android_poll_source;
109 Pandroid_app = ^Tandroid_app;
110 android_poll_source = packed record
111 // The identifier of this source. May be LOOPER_ID_MAIN or
112 // LOOPER_ID_INPUT.
113 id : cint32;
114 // The android_app this ident is associated with.
115 app : Pandroid_app;
116 // Function to call to perform the standard processing of data from
117 // this source.
118 process : procedure(app: Pandroid_app; source: Pandroid_poll_source);
119 end;
120
121 (**
122 * This is the interface for the standard glue code of a threaded
123 * application. In this model, the application's code is running
124 * in its own thread separate from the main thread of the process.
125 * It is not required that this thread be associated with the Java
126 * VM, although it will need to be in order to make JNI calls any
127 * Java objects.
128 *)
129 Tandroid_app = packed record
130 // The application can place a pointer to its own state object
131 // here if it likes.
132 userData : Pointer;
133 // Fill this in with the function to process main app commands (APP_CMD_*)
134 onAppCmd : procedure(app: Pandroid_app; cmd: Integer) of object;
135 // Fill this in with the function to process input events. At this point
136 // the event has already been pre-dispatched, and it will be finished upon
137 // return. Return if you have handled the event, 0 for any default
138 // dispatching.
139 onInputEvent : function(app: Pandroid_app; event: PAInputEvent): boolean of object;
140 // The ANativeActivity object instance that this app is running in.
141 activity : PANativeActivity;
142 // The current configuration the app is running in.
143 config : PAConfiguration;
144 // This is the last instance's saved state, as provided at creation time.
145 // It is NULL if there was no state. You can use this as you need; the
146 // memory will remain around until you call android_app_exec_cmd() for
147 // APP_CMD_RESUME, at which point it will be freed and savedState set to NULL.
148 // These variables should only be changed when processing a APP_CMD_SAVE_STATE,
149 // at which point they will be initialized to NULL and you can malloc your
150 // state and place the information here. In that case the memory will be
151 // freed for you later.
152 savedState : Pointer;
153 savedStateSize : csize_t;
154 // The ALooper associated with the app's thread.
155 looper : PALooper;
156 // When non-NULL, this is the input queue from which the app will
157 // receive user input events.
158 inputQueue : PAInputQueue;
159 // When non-NULL, this is the window surface that the app can draw in.
160 window : PANativeWindow;
161 // Current content rectangle of the window; this is the area where the
162 // window's content should be placed to be seen by the user.
163 contentRect : ARect;
164 // Current state of the app's activity. May be either APP_CMD_START,
165 // APP_CMD_RESUME, APP_CMD_PAUSE, or APP_CMD_STOP; see below.
166 activityState : cint;
167 // This is non-zero when the application's NativeActivity is being
168 // destroyed and waiting for the app thread to complete.
169 destroyRequested : cint;
170 // -------------------------------------------------
171 // Below are "private" implementation of the glue code.
172 mutex : pthread_mutex_t;
173 cond : pthread_cond_t;
174 msgread : cint;
175 msgwrite : cint;
176 cmdPollSource : android_poll_source;
177 inputPollSource : android_poll_source;
178 running : cint;
179 stateSaved : cint;
180 destroyed : cint;
181 redrawNeeded : cint;
182 pendingInputQueue : PAInputQueue;
183 pendingWindow : PANativeWindow;
184 pendingContentRect : ARect;
185 end;
186
187 const
188 (**
189 * Looper data ID of commands coming from the app's main thread, which
190 * is returned as an identifier from ALooper_pollOnce(). The data for this
191 * identifier is a pointer to an android_poll_source structure.
192 * These can be retrieved and processed with android_app_read_cmd()
193 * and android_app_exec_cmd().
194 *)
195 LOOPER_ID_MAIN = 1;
196 (**
197 * Looper data ID of events coming from the AInputQueue of the
198 * application's window, which is returned as an identifier from
199 * ALooper_pollOnce(). The data for this identifier is a pointer to an
200 * android_poll_source structure. These can be read via the inputQueue
201 * object of android_app.
202 *)
203 LOOPER_ID_INPUT = 2;
204 (**
205 * Start of user-defined ALooper identifiers.
206 *)
207 LOOPER_ID_USER = 3;
208
209 const
210 (**
211 * Command from main thread: the AInputQueue has changed. Upon processing
212 * this command, android_app->inputQueue will be updated to the new queue
213 * (or NULL).
214 *)
215 APP_CMD_INPUT_CHANGED = 0;
216 (**
217 * Command from main thread: a new ANativeWindow is ready for use. Upon
218 * receiving this command, android_app->window will contain the new window
219 * surface.
220 *)
221 APP_CMD_INIT_WINDOW = 1;
222 (**
223 * Command from main thread: the existing ANativeWindow needs to be
224 * terminated. Upon receiving this command, android_app->window still
225 * contains the existing window; after calling android_app_exec_cmd
226 * it will be set to NULL.
227 *)
228 APP_CMD_TERM_WINDOW = 2;
229 (**
230 * Command from main thread: the current ANativeWindow has been resized.
231 * Please redraw with its new size.
232 *)
233 APP_CMD_WINDOW_RESIZED = 3;
234 (**
235 * Command from main thread: the system needs that the current ANativeWindow
236 * be redrawn. You should redraw the window before handing this to
237 * android_app_exec_cmd() in order to avoid transient drawing glitches.
238 *)
239 APP_CMD_WINDOW_REDRAW_NEEDED = 4;
240 (**
241 * Command from main thread: the content area of the window has changed,
242 * such as from the soft input window being shown or hidden. You can
243 * find the new content rect in android_app::contentRect.
244 *)
245 APP_CMD_CONTENT_RECT_CHANGED = 5;
246 (**
247 * Command from main thread: the app's activity window has gained
248 * input focus.
249 *)
250 APP_CMD_GAINED_FOCUS = 6;
251 (**
252 * Command from main thread: the app's activity window has lost
253 * input focus.
254 *)
255 APP_CMD_LOST_FOCUS = 7;
256 (**
257 * Command from main thread: the current device configuration has changed.
258 *)
259 APP_CMD_CONFIG_CHANGED = 8;
260 (**
261 * Command from main thread: the system is running low on memory.
262 * Try to reduce your memory use.
263 *)
264 APP_CMD_LOW_MEMORY = 9;
265 (**
266 * Command from main thread: the app's activity has been started.
267 *)
268 APP_CMD_START = 10;
269 (**
270 * Command from main thread: the app's activity has been resumed.
271 *)
272 APP_CMD_RESUME = 11;
273 (**
274 * Command from main thread: the app should generate a new saved state
275 * for itself, to restore from later if needed. If you have saved state,
276 * allocate it with malloc and place it in android_app.savedState with
277 * the size in android_app.savedStateSize. The will be freed for you
278 * later.
279 *)
280 APP_CMD_SAVE_STATE = 12;
281 (**
282 * Command from main thread: the app's activity has been paused.
283 *)
284 APP_CMD_PAUSE = 13;
285 (**
286 * Command from main thread: the app's activity has been stopped.
287 *)
288 APP_CMD_STOP = 14;
289 (**
290 * Command from main thread: the app's activity is being destroyed,
291 * and waiting for the app thread to clean up and exit before proceeding.
292 *)
293 APP_CMD_DESTROY = 15;
294
295 type
296 TAndroidMainFunction = procedure (App: PAndroid_App);
297 var
298 AndroidMain: TAndroidMainFunction;
299
300 { This function is exported from the library. It implements the activity,
301 passing the control to AndroidMain callback.
302
303 Note that this function *can* be called many times.
304 The activity may be destroyed and then created again.
305 The actual process *may* stay running.
306 (to test, try "Developer Options -> Always Destroy Activity"). }
307 procedure ANativeActivity_onCreate(activity: PANativeActivity; savedState: Pointer; savedStateSize: csize_t); cdecl;
308
309 { Allocate memory for saved state. }
310 function AllocateSavedState(const Size: csize_t): Pointer;
311
312 var
313 { Singleton instance of PAndroid_App, initialized right before AndroidMain is called. }
314 AndroidMainApp: PAndroid_App;
315
316 implementation
317
318 uses SysUtils, Classes, CastleUtils;
319
320 { Use Libc memory allocation routines where needed. It seems savedState
321 must be managed using them, onSaveInstanceState in CastleAndroidInternalNativeActivity
322 is documented like that. }
323 const
324 CLibName = 'c';
325 Function LibcMalloc (Size : ptruint) : Pointer; cdecl; external CLibName name 'malloc';
326 Procedure LibcFree (P : pointer); cdecl; external CLibName name 'free';
327
328 type
329 ppthread_t = ^pthread_t;
330 ppthread_mutex_t = ^pthread_mutex_t;
331 ppthread_cond_t = ^pthread_cond_t;
332 ppthread_mutexattr_t = ^pthread_mutexattr_t;
333 ppthread_condattr_t = ^pthread_condattr_t;
334
335 function pthread_mutex_init(__mutex:ppthread_mutex_t; __mutex_attr:ppthread_mutexattr_t):CInt32;cdecl;external 'libc.so';
336 function pthread_mutex_destroy(__mutex:ppthread_mutex_t):CInt32;cdecl;external 'libc.so';
337 function pthread_mutex_lock(__mutex: ppthread_mutex_t):CInt32;cdecl;external 'libc.so';
338 function pthread_mutex_unlock(__mutex: ppthread_mutex_t):CInt32;cdecl;external 'libc.so';
339 function pthread_cond_init(__cond:ppthread_cond_t; __cond_attr:ppthread_condattr_t):CInt32;cdecl;external 'libc.so';
340 function pthread_cond_destroy(__cond:ppthread_cond_t):CInt32;cdecl;external 'libc.so';
341 function pthread_cond_signal(__cond:ppthread_cond_t):CInt32;cdecl;external 'libc.so';
342 function pthread_cond_broadcast(__cond:ppthread_cond_t):CInt32;cdecl;external 'libc.so';
343 function pthread_cond_wait(__cond:ppthread_cond_t; __mutex:ppthread_mutex_t):CInt32;cdecl;external 'libc.so';
344
345 procedure FreeSavedState(android_app: Pandroid_app);
346 begin
347 pthread_mutex_lock(@android_app^.mutex);
348 if android_app^.savedState <> Nil then
349 begin
350 LibcFree(android_app^.savedState);
351 android_app^.savedState := nil;
352 android_app^.savedStateSize := 0;
353 end;
354 pthread_mutex_unlock(@android_app^.mutex);
355 end;
356
357 (**
358 * Call when ALooper_pollAll() returns LOOPER_ID_MAIN, reading the next
359 * app command message.
360 *)
361 function android_app_read_cmd(android_app: Pandroid_app): cint8;
362 var cmd: cint8;
363 begin
364 result := -1;
365 if fpread(android_app^.msgread, @cmd, sizeof(cmd)) = sizeof(cmd) then
366 begin
367 case cmd of
368 APP_CMD_SAVE_STATE:
369 FreeSavedState(android_app);
370 end;
371 result := cmd;
372 end
373 else
374 AndroidLog(alError, 'NativeAppGlue: No data on command pipe');
375 end;
376
377 (**
378 * Call with the command returned by android_app_read_cmd() to do the
379 * initial pre-processing of the given command. You can perform your own
380 * actions for the command after calling this function.
381 *)
382 procedure android_app_pre_exec_cmd(android_app: Pandroid_app; cmd: cint8);
383 begin
384 case cmd of
385 APP_CMD_INPUT_CHANGED:
386 begin
387 AndroidLog(alInfo,'NativeAppGlue: APP_CMD_INPUT_CHANGED');
388 pthread_mutex_lock(@android_app^.mutex);
389 if android_app^.inputQueue <> nil then
390 AInputQueue_detachLooper(android_app^.inputQueue);
391 android_app^.inputQueue := android_app^.pendingInputQueue;
392 if android_app^.inputQueue <> nil then
393 begin
394 AndroidLog(alInfo,'NativeAppGlue: Attaching input queue to looper');
395 AInputQueue_attachLooper(android_app^.inputQueue,
396 android_app^.looper, LOOPER_ID_INPUT, nil,
397 @android_app^.inputPollSource);
398 end;
399 pthread_cond_broadcast(@android_app^.cond);
400 pthread_mutex_unlock(@android_app^.mutex);
401 end;
402
403 APP_CMD_INIT_WINDOW:
404 begin
405 AndroidLog(alInfo,'NativeAppGlue: APP_CMD_INIT_WINDOW');
406 pthread_mutex_lock(@android_app^.mutex);
407 android_app^.window := android_app^.pendingWindow;
408 pthread_cond_broadcast(@android_app^.cond);
409 pthread_mutex_unlock(@android_app^.mutex);
410 end;
411
412 APP_CMD_TERM_WINDOW:
413 begin
414 AndroidLog(alInfo,'NativeAppGlue: APP_CMD_TERM_WINDOW');
415 pthread_mutex_lock(@android_app^.mutex);
416 android_app^.window := nil;
417 pthread_cond_broadcast(@android_app^.cond);
418 pthread_mutex_unlock(@android_app^.mutex);
419 end;
420
421 APP_CMD_RESUME,
422 APP_CMD_START,
423 APP_CMD_PAUSE,
424 APP_CMD_STOP:
425 begin
426 // AndroidLog(alInfo,'NativeAppGlue: activityState:=%d', [cmd]);
427 pthread_mutex_lock(@android_app^.mutex);
428 android_app^.activityState := cmd;
429 pthread_cond_broadcast(@android_app^.cond);
430 pthread_mutex_unlock(@android_app^.mutex);
431 end;
432
433 APP_CMD_CONFIG_CHANGED:
434 begin
435 AndroidLog(alInfo,'NativeAppGlue: APP_CMD_CONFIG_CHANGED');
436 AConfiguration_fromAssetManager(android_app^.config,
437 android_app^.activity^.assetManager);
438 end;
439
440 APP_CMD_DESTROY:
441 begin
442 AndroidLog(alInfo,'NativeAppGlue: APP_CMD_DESTROY');
443 android_app^.destroyRequested := 1;
444 end;
445 end;
446 end;
447
448 (**
449 * Call with the command returned by android_app_read_cmd() to do the
450 * final post-processing of the given command. You must have done your own
451 * actions for the command before calling this function.
452 *)
453 procedure android_app_post_exec_cmd(android_app: Pandroid_app; cmd: cint8);
454 begin
455 case cmd of
456 APP_CMD_TERM_WINDOW:
457 begin
458 AndroidLog(alInfo,'NativeAppGlue: APP_CMD_TERM_WINDOW');
459 pthread_mutex_lock(@android_app^.mutex);
460 android_app^.window := nil;
461 pthread_cond_broadcast(@android_app^.cond);
462 pthread_mutex_unlock(@android_app^.mutex);
463 end;
464
465 APP_CMD_SAVE_STATE:
466 begin
467 AndroidLog(alInfo,'NativeAppGlue: APP_CMD_SAVE_STATE');
468 pthread_mutex_lock(@android_app^.mutex);
469 android_app^.stateSaved := 1;
470 pthread_cond_broadcast(@android_app^.cond);
471 pthread_mutex_unlock(@android_app^.mutex);
472 end;
473
474 APP_CMD_RESUME:
475 FreeSavedState(android_app);
476 end;
477 end;
478
479 procedure android_app_destroy(android_app: Pandroid_app);
480 begin
481 AndroidLog(alInfo, 'NativeAppGlue: android_app_destroy');
482 FreeSavedState(android_app);
483 pthread_mutex_lock(@android_app^.mutex);
484 if (android_app^.inputQueue <> nil) then
485 AInputQueue_detachLooper(android_app^.inputQueue);
486 AConfiguration_delete(android_app^.config);
487 android_app^.destroyed := 1;
488 pthread_cond_broadcast(@android_app^.cond);
489 pthread_mutex_unlock(@android_app^.mutex);
490 // Can't touch android_app object after this.
491 end;
492
493 procedure process_input(app: Pandroid_app; source: Pandroid_poll_source);
494 var
495 Event: PAInputEvent;
496 Handled, Processed: boolean;
497 begin
498 { Original native_app_glue was using if and processing only 1 event.
499 Fixed to avoid ANRs following
500 https://developer.nvidia.com/content/nativeactivity-input-crashes-and-anrs-simple-fix-dangerous-bug }
501 Event := nil;
502 Processed := false;
503 while AInputQueue_getEvent(app^.inputQueue, @event) >= 0 do
504 begin
505 // AndroidLog(alInfo,'NativeAppGlue: New input event: type:=%d',[AInputEvent_getType(event)]);
506 if AInputQueue_preDispatchEvent(app^.inputQueue, event) <> 0 then
507 Continue;
508 Handled := false;
509 if Assigned(app^.onInputEvent) then
510 Handled := App^.onInputEvent(app, event);
511 AInputQueue_finishEvent(app^.inputQueue, event, handled);
512 Processed := true;
513 end;
514 if not Processed then
515 AndroidLog(alError, 'NativeAppGlue: Failure reading next input event');
516 end;
517
518 procedure process_cmd(app: Pandroid_app; source: Pandroid_poll_source);
519 var cmd: cint8;
520 begin
521 cmd := android_app_read_cmd(app);
522 android_app_pre_exec_cmd(app, cmd);
523 if (app^.onAppCmd <> nil) then app^.onAppCmd(app, cmd);
524 android_app_post_exec_cmd(app, cmd);
525 end;
526
527 type
528 TAndroidAppThread = class(TThread)
529 Android_app: PAndroid_app;
530 constructor Create(AnAndroid_app: PAndroid_app; const CreateSuspended: boolean);
531 procedure Execute; override;
532 end;
533
534 constructor TAndroidAppThread.Create(AnAndroid_app: PAndroid_app;
535 const CreateSuspended: boolean);
536 begin
537 Android_app := AnAndroid_app;
538 inherited Create(CreateSuspended);
539 end;
540
541 procedure TAndroidAppThread.Execute;
542 var
543 looper: PALooper;
544 begin
545 try
546 AndroidLog(alInfo, 'NativeAppGlue: TAndroidAppThread.Execute');
547
548 android_app^.config := AConfiguration_new();
549 AConfiguration_fromAssetManager(android_app^.config, android_app^.activity^.assetManager);
550
551 android_app^.cmdPollSource.id := LOOPER_ID_MAIN;
552 android_app^.cmdPollSource.app := android_app;
553 android_app^.cmdPollSource.process := @process_cmd;
554 android_app^.inputPollSource.id := LOOPER_ID_INPUT;
555 android_app^.inputPollSource.app := android_app;
556 android_app^.inputPollSource.process := @process_input;
557
558 looper := ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
559 ALooper_addFd(looper, android_app^.msgread, LOOPER_ID_MAIN, ALOOPER_EVENT_INPUT, nil,
560 @android_app^.cmdPollSource);
561 android_app^.looper := looper;
562
563 pthread_mutex_lock(@android_app^.mutex);
564 android_app^.running := 1;
565 pthread_cond_broadcast(@android_app^.cond);
566 pthread_mutex_unlock(@android_app^.mutex);
567
568 { Looks like this has to be in it's own try..except handler,
569 other a crash can occur when catching exceptions from inside AndroidMain.
570 Not really known why.
571 Reproducible by drawing_toy with deliberately crashing DrawCore.
572 (Possibly not needed anymore, since using TAndroidAppThread?). }
573 try
574 AndroidMainApp := android_app;
575 AndroidMain(android_app);
576 except
577 on E: TObject do
578 AndroidLog(alError, 'NativeAppGlue: AndroidMain exited with exception: ' + ExceptMessage(E));
579 end;
580
581 android_app_destroy(android_app);
582 except
583 on E: TObject do
584 AndroidLog(alError, 'NativeAppGlue: TAndroidAppThread.Execute exited with exception: ' + ExceptMessage(E));
585 end;
586 end;
587
588 // --------------------------------------------------------------------
589 // Native activity interaction (called from main thread)
590 // --------------------------------------------------------------------
591
592 function AllocateSavedState(const Size: csize_t): Pointer;
593 begin
594 Result := LibcMalloc(Size);
595 end;
596
597 function android_app_create(activity: PANativeActivity; savedState: Pointer; savedStateSize: csize_t): Pandroid_app;
598 var
599 msgpipe: array[0..1] of cint;
600 android_app: Pandroid_app;
601 Thread: TAndroidAppThread;
602 begin
603 android_app := Pandroid_app(LibcMalloc(sizeof(Tandroid_app)));
604 fillchar(android_app^, sizeof(tandroid_app), 0);
605 android_app^.activity := activity;
606
607 pthread_mutex_init(@android_app^.mutex, nil);
608 pthread_cond_init(@android_app^.cond, nil);
609
610 if (savedState <> nil) then
611 begin
612 AndroidLog(alInfo, Format('NativeAppGlue: Got state to load, size %d', [savedStateSize]));
613 android_app^.savedState := AllocateSavedState(savedStateSize);
614 android_app^.savedStateSize := savedStateSize;
615 move(pbyte(savedState)^, pbyte(android_app^.savedState)^, savedStateSize);
616 end;
617
618 if FpPipe(msgpipe) <> 0 then
619 AndroidLog(alError, 'NativeAppGlue: Could not create pipe');
620
621 android_app^.msgread := msgpipe[0];
622 android_app^.msgwrite := msgpipe[1];
623
624 Thread := TAndroidAppThread.Create(Android_app, false);
625 Thread.FreeOnTerminate := true;
626
627 // Wait for thread to start.
628 pthread_mutex_lock(@android_app^.mutex);
629 while android_app^.running = 0 do
630 pthread_cond_wait(@android_app^.cond, @android_app^.mutex);
631 pthread_mutex_unlock(@android_app^.mutex);
632
633 result := android_app;
634 end;
635
636 procedure android_app_write_cmd(android_app: Pandroid_app; cmd: cint8);
637 begin
638 if fpwrite(android_app^.msgwrite, cmd, sizeof(cmd)) <> sizeof(cmd) then
639 AndroidLog(alError, 'NativeAppGlue: Failure writing android_app cmd');
640 end;
641
642 procedure android_app_set_input(android_app: Pandroid_app; inputQueue: PAInputQueue);
643 begin
644 pthread_mutex_lock(@android_app^.mutex);
645 android_app^.pendingInputQueue := inputQueue;
646 android_app_write_cmd(android_app, APP_CMD_INPUT_CHANGED);
647 while (android_app^.inputQueue <> android_app^.pendingInputQueue) do
648 pthread_cond_wait(@android_app^.cond, @android_app^.mutex);
649 pthread_mutex_unlock(@android_app^.mutex);
650 end;
651
652 procedure android_app_set_window(android_app: Pandroid_app; window: PANativeWindow);
653 begin
654 pthread_mutex_lock(@android_app^.mutex);
655 if (android_app^.pendingWindow <> nil) then
656 android_app_write_cmd(android_app, APP_CMD_TERM_WINDOW);
657
658 android_app^.pendingWindow := window;
659 if (window <> nil) then
660 android_app_write_cmd(android_app, APP_CMD_INIT_WINDOW);
661
662 while (android_app^.window <> android_app^.pendingWindow) do
663 pthread_cond_wait(@android_app^.cond, @android_app^.mutex);
664
665 pthread_mutex_unlock(@android_app^.mutex);
666 end;
667
668 procedure android_app_set_activity_state(android_app: Pandroid_app; cmd: cint8);
669 begin
670 // AndroidLog(alInfo,' NativeAppGlue: Setting activity state to %d', [cmd]);
671 pthread_mutex_lock(@android_app^.mutex);
672 android_app_write_cmd(android_app, cmd);
673 while (android_app^.activityState <> cmd) do
674 pthread_cond_wait(@android_app^.cond, @android_app^.mutex);
675
676 pthread_mutex_unlock(@android_app^.mutex);
677 end;
678
679 procedure android_app_free(android_app: Pandroid_app);
680 begin
681 pthread_mutex_lock(@android_app^.mutex);
682 android_app_write_cmd(android_app, APP_CMD_DESTROY);
683 while android_app^.destroyed = 0 do
684 pthread_cond_wait(@android_app^.cond, @android_app^.mutex);
685
686 pthread_mutex_unlock(@android_app^.mutex);
687
688 fpclose(android_app^.msgread);
689 fpclose(android_app^.msgwrite);
690 pthread_cond_destroy(@android_app^.cond);
691 pthread_mutex_destroy(@android_app^.mutex);
692 LibcFree(android_app);
693 end;
694
695 procedure onDestroy(activity: PANativeActivity); cdecl;
696 begin
697 try
698 AndroidLog(alInfo, 'NativeAppGlue: onDestroy');
699 android_app_free(Pandroid_app(activity^.instance));
700 except
701 on E: TObject do
702 AndroidLog(alError, 'NativeAppGlue: onDestroy exited with exception: ' + ExceptMessage(E));
703 end;
704 end;
705
706 procedure onStart(activity: PANativeActivity); cdecl;
707 begin
708 try
709 AndroidLog(alInfo, 'NativeAppGlue: onStart');
710 android_app_set_activity_state(Pandroid_app(activity^.instance), APP_CMD_START);
711 except
712 on E: TObject do
713 AndroidLog(alError, 'NativeAppGlue: onStart exited with exception: ' + ExceptMessage(E));
714 end;
715 end;
716
717 procedure onResume(activity: PANativeActivity); cdecl;
718 begin
719 try
720 AndroidLog(alInfo, 'NativeAppGlue: onResume');
721 android_app_set_activity_state(Pandroid_app(activity^.instance), APP_CMD_RESUME);
722 except
723 on E: TObject do
724 AndroidLog(alError, 'NativeAppGlue: onResume exited with exception: ' + ExceptMessage(E));
725 end;
726 end;
727
728 function onSaveInstanceState(activity: PANativeActivity; outLen: pcsize_t): Pointer; cdecl;
729 var android_app: Pandroid_app;
730 savedState: pointer;
731 begin
732 result := nil;
733 outLen^ := 0;
734
735 try
736 android_app := activity^.instance;
737 savedState := nil;
738
739 AndroidLog(alInfo, 'NativeAppGlue: onSaveInstanceState');
740 pthread_mutex_lock(@android_app^.mutex);
741 android_app^.stateSaved := 0;
742 android_app_write_cmd(android_app, APP_CMD_SAVE_STATE);
743 while android_app^.stateSaved = 0 do
744 pthread_cond_wait(@android_app^.cond, @android_app^.mutex);
745
746 if android_app^.savedState <> nil then
747 begin
748 savedState := android_app^.savedState;
749 outLen^ := android_app^.savedStateSize;
750 android_app^.savedState := nil;
751 android_app^.savedStateSize := 0;
752 AndroidLog(alInfo, Format('NativeAppGlue: Got state to save, size %d', [outLen^]));
753 end;
754
755 pthread_mutex_unlock(@android_app^.mutex);
756
757 result := savedState;
758 except
759 on E: TObject do
760 AndroidLog(alError, 'NativeAppGlue: onSaveInstanceState exited with exception: ' + ExceptMessage(E));
761 end;
762 end;
763
764 procedure onPause(activity: PANativeActivity); cdecl;
765 begin
766 try
767 AndroidLog(alInfo, 'NativeAppGlue: onPause');
768 android_app_set_activity_state(Pandroid_app(activity^.instance), APP_CMD_PAUSE);
769 except
770 on E: TObject do
771 AndroidLog(alError, 'NativeAppGlue: onStop exited with exception: ' + ExceptMessage(E));
772 end;
773 end;
774
775 procedure onStop(activity: PANativeActivity); cdecl;
776 begin
777 try
778 AndroidLog(alInfo, 'NativeAppGlue: onStop');
779 android_app_set_activity_state(Pandroid_app(activity^.instance), APP_CMD_STOP);
780 except
781 on E: TObject do
782 AndroidLog(alError, 'NativeAppGlue: onStop exited with exception: ' + ExceptMessage(E));
783 end;
784 end;
785
786 procedure onConfigurationChanged(activity: PANativeActivity); cdecl;
787 var android_app: Pandroid_app;
788 begin
789 try
790 android_app := activity^.instance;
791 AndroidLog(alInfo, 'NativeAppGlue: onConfigurationChanged');
792 android_app_write_cmd(android_app, APP_CMD_CONFIG_CHANGED);
793 except
794 on E: TObject do
795 AndroidLog(alError, 'NativeAppGlue: onConfigurationChanged exited with exception: ' + ExceptMessage(E));
796 end;
797 end;
798
799 procedure onLowMemory(activity: PANativeActivity); cdecl;
800 var android_app: Pandroid_app;
801 begin
802 try
803 android_app := activity^.instance;
804 AndroidLog(alInfo, 'NativeAppGlue: onLowMemory');
805 android_app_write_cmd(android_app, APP_CMD_LOW_MEMORY);
806 except
807 on E: TObject do
808 AndroidLog(alError, 'NativeAppGlue: onLowMemory exited with exception: ' + ExceptMessage(E));
809 end;
810 end;
811
812 procedure onWindowFocusChanged(activity: PANativeActivity; focused: cint); cdecl;
813 begin
814 try
815 AndroidLog(alInfo, 'NativeAppGlue: onWindowFocusChanged');
816
817 if focused <> 0 then
818 android_app_write_cmd(activity^.instance, APP_CMD_GAINED_FOCUS)
819 else
820 android_app_write_cmd(activity^.instance, APP_CMD_LOST_FOCUS);
821 except
822 on E: TObject do
823 AndroidLog(alError, 'NativeAppGlue: onWindowFocusChanged exited with exception: ' + ExceptMessage(E));
824 end;
825 end;
826
827 procedure onNativeWindowCreated(activity: PANativeActivity; window: PANativeWindow); cdecl;
828 begin
829 try
830 AndroidLog(alInfo, 'NativeAppGlue: onNativeWindowCreated');
831 android_app_set_window(activity^.instance, window);
832 except
833 on E: TObject do
834 AndroidLog(alError, 'NativeAppGlue: onNativeWindowCreated exited with exception: ' + ExceptMessage(E));
835 end;
836 end;
837
838 procedure onNativeWindowDestroyed(activity: PANativeActivity; window: PANativeWindow); cdecl;
839 begin
840 try
841 AndroidLog(alInfo, 'NativeAppGlue: onNativeWindowDestroyed');
842 android_app_set_window(activity^.instance, nil);
843 except
844 on E: TObject do
845 AndroidLog(alError, 'NativeAppGlue: onNativeWindowDestroyed exited with exception: ' + ExceptMessage(E));
846 end;
847 end;
848
849 procedure onInputQueueCreated(activity: PANativeActivity; queue: PAInputQueue); cdecl;
850 begin
851 try
852 AndroidLog(alInfo, 'NativeAppGlue: onInputQueueCreated');
853 android_app_set_input(activity^.instance, queue);
854 except
855 on E: TObject do
856 AndroidLog(alError, 'NativeAppGlue: onInputQueueCreated exited with exception: ' + ExceptMessage(E));
857 end;
858 end;
859
860 procedure onInputQueueDestroyed(activity: PANativeActivity; queue: PAInputQueue); cdecl;
861 begin
862 try
863 AndroidLog(alInfo, 'NativeAppGlue: onInputQueueDestroyed');
864 android_app_set_input(activity^.instance, nil);
865 except
866 on E: TObject do
867 AndroidLog(alError, 'NativeAppGlue: onInputQueueDestroyed exited with exception: ' + ExceptMessage(E));
868 end;
869 end;
870
871 procedure ANativeActivity_onCreate(activity: PANativeActivity; savedState: Pointer; savedStateSize: csize_t); cdecl;
872 begin
873 try
874 AndroidLog(alInfo, 'NativeAppGlue: ANativeActivity_onCreate called, creating activity');
875
876 activity^.callbacks^.onDestroy := @onDestroy;
877 activity^.callbacks^.onStart := @onStart;
878 activity^.callbacks^.onStop := @onStop;
879 activity^.callbacks^.onPause := @onPause;
880 activity^.callbacks^.onResume := @onResume;
881
882 activity^.callbacks^.onNativeWindowCreated := @onNativeWindowCreated;
883 activity^.callbacks^.onNativeWindowDestroyed := @onNativeWindowDestroyed;
884
885 activity^.callbacks^.onSaveInstanceState := @onSaveInstanceState;
886 activity^.callbacks^.onConfigurationChanged := @onConfigurationChanged;
887 activity^.callbacks^.onLowMemory := @onLowMemory;
888 activity^.callbacks^.onWindowFocusChanged := @onWindowFocusChanged;
889 activity^.callbacks^.onInputQueueCreated := @onInputQueueCreated;
890 activity^.callbacks^.onInputQueueDestroyed := @onInputQueueDestroyed;
891
892 activity^.instance := android_app_create(activity, savedState, savedStateSize);
893 except
894 on E: TObject do
895 AndroidLog(alError, 'NativeAppGlue: ANativeActivity_onCreate exited with exception: ' + ExceptMessage(E));
896 end;
897 end;
898
899 end.