| 1 |
{%MainUnit castlewindow.pas} |
| 2 |
{ |
| 3 |
Copyright 2004-2024 Michalis Kamburelis. |
| 4 |
|
| 5 |
This file is part of "Castle Game Engine". |
| 6 |
|
| 7 |
"Castle Game Engine" is free software; see the file COPYING.txt, |
| 8 |
included in this distribution, for details about the copyright. |
| 9 |
|
| 10 |
"Castle Game Engine" is distributed in the hope that it will be useful, |
| 11 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 13 |
|
| 14 |
---------------------------------------------------------------------------- |
| 15 |
} |
| 16 |
|
| 17 |
{ Manage OpenGL ES context on Android using EGL, |
| 18 |
and manage message loop using Android NDK. } |
| 19 |
|
| 20 |
{$I castlewindow_egl.inc} |
| 21 |
{$I castlewindow_dialogs_by_messages.inc} |
| 22 |
|
| 23 |
{ Load / save Config when activity is sleeping / woken up. |
| 24 |
|
| 25 |
This does not provide a real persistence, so it's of limited use, |
| 26 |
and actually would cause problems if you use real persistence |
| 27 |
(like http://developer.android.com/guide/topics/data/data-storage.html) |
| 28 |
since you would not know which to trust --- the persistent file, |
| 29 |
or stuff provided by application load state? |
| 30 |
So for now, it's not used. } |
| 31 |
{ $define CASTLE_PERSISTENT_ANDROID_STATE} |
| 32 |
|
| 33 |
{$ifdef read_interface_uses} |
| 34 |
CastleAndroidInternalNativeWindow, CastleAndroidInternalInput, |
| 35 |
CastleAndroidNativeAppGlue, |
| 36 |
{$endif} |
| 37 |
|
| 38 |
{$ifdef read_implementation_uses} |
| 39 |
JNI, |
| 40 |
CastleAndroidInternalCWString, CastleAndroidInternalLooper, |
| 41 |
CastleAndroidInternalLog, CastleAndroidInternalAssetStream, |
| 42 |
CastleAndroidInternalConfiguration, |
| 43 |
{$ifdef CASTLE_PERSISTENT_ANDROID_STATE} CastleConfig, {$endif} CastleDynLib, |
| 44 |
{$ifdef CASTLE_PNG_DYNAMIC} CastleInternalPng, {$endif} |
| 45 |
CastleInternalOpenAL, CastleInternalVorbisFile, CastleInternalFreeTypeH, |
| 46 |
CastleInternalZLib, |
| 47 |
{$endif} |
| 48 |
|
| 49 |
{$ifdef read_window_interface} |
| 50 |
private |
| 51 |
NativeWindow: EGLNativeWindowType; //< must be set before Window.Open |
| 52 |
function HandleOnScreenKeyboard(const Received: TCastleStringList; |
| 53 |
const ReceivedStream: TMemoryStream): boolean; |
| 54 |
|
| 55 |
function AndroidKeyCodeToKey(const AndroidKeyCode: Integer): TKey; |
| 56 |
{$endif read_window_interface} |
| 57 |
|
| 58 |
{$ifdef read_application_interface} |
| 59 |
private |
| 60 |
type |
| 61 |
{ On Android, we have to track previous touch positions using our |
| 62 |
own structure, instead of relying on |
| 63 |
MainWindow.FTouches.FingerIndexPosition[FingerIndex]. |
| 64 |
|
| 65 |
Reason: DoMotion is not immediately called when |
| 66 |
receiving AMOTION_EVENT_ACTION_MOVE. That is bacause we have to do |
| 67 |
our own event loop, that is emptied after native_app_glue is emptied, |
| 68 |
so we may process many AMOTION_EVENT_ACTION_MOVE before calling |
| 69 |
DoMotion for them. |
| 70 |
This is a consequence of native_app_glue weirdness, that forces us to process |
| 71 |
AMOTION_EVENT_ACTION_MOVE immediately, while calling DoMotion may take a while |
| 72 |
(esp. if it calls Application.ProcessMessage). } |
| 73 |
TTouchChange = object |
| 74 |
OldPosition, Position: TVector2; |
| 75 |
end; |
| 76 |
|
| 77 |
TQueuedEventType = (aeOpen, aeMotionDown, aeMotionUp, aeMotionMove); |
| 78 |
TQueuedEvent = object |
| 79 |
EventType: TQueuedEventType; |
| 80 |
Touch: TTouchChange; |
| 81 |
FingerIndex: TFingerIndex; |
| 82 |
end; |
| 83 |
TQueuedEventList = specialize TList<TQueuedEvent>; |
| 84 |
|
| 85 |
const |
| 86 |
FingerCount = 20; |
| 87 |
|
| 88 |
var |
| 89 |
FScreenWidth, FScreenHeight: Integer; |
| 90 |
QEvents: TQueuedEventList; |
| 91 |
TouchChanges: array [0..FingerCount - 1] of TTouchChange; |
| 92 |
ResumeScheduled: boolean; |
| 93 |
|
| 94 |
function HandleInput(App: PAndroid_app; Event: PAInputEvent): boolean; |
| 95 |
procedure HandleCommand(App: PAndroid_app; Command: Integer); |
| 96 |
{$endif read_application_interface} |
| 97 |
|
| 98 |
{$ifdef read_implementation_uses} |
| 99 |
{$endif} |
| 100 |
|
| 101 |
{$ifdef read_implementation} |
| 102 |
|
| 103 |
{ Android NDK integration ---------------------------------------------------- } |
| 104 |
|
| 105 |
procedure OpenContext; |
| 106 |
var |
| 107 |
Width, Height: Integer; |
| 108 |
Window: TCastleWindow; |
| 109 |
NativeWindow: PANativeWindow; |
| 110 |
begin |
| 111 |
Window := Application.MainWindow; |
| 112 |
NativeWindow := Window.NativeWindow; // NativeWindow was saved here by HandleCommand |
| 113 |
|
| 114 |
{ get window size, use it } |
| 115 |
Width := ANativeWindow_getWidth(NativeWindow); |
| 116 |
Height := ANativeWindow_getHeight(NativeWindow); |
| 117 |
AndroidLog(alInfo, 'OpenContext (size: %d %d)', [Width, Height]); |
| 118 |
Application.FScreenWidth := Width; |
| 119 |
Application.FScreenHeight := Height; |
| 120 |
//Window.FullScreen := true; // TODO: setting fullscreen should work like that 4 lines below. Also, should be default? |
| 121 |
Window.FLeft := 0; |
| 122 |
Window.FTop := 0; |
| 123 |
Window.FWidth := Width; |
| 124 |
Window.FHeight := Height; |
| 125 |
|
| 126 |
{ in case we're getting back to foreground, from sleeping / background, |
| 127 |
do not treat huge "time passed" as meaningful in next Update. |
| 128 |
Note: MaxSensibleSecondsPassed would limit this problem anyway, |
| 129 |
but still it's better to just make it zero. } |
| 130 |
Window.Fps.ZeroNextSecondsPassed; |
| 131 |
|
| 132 |
{ create OpenGL context, run OnOpen events and so on } |
| 133 |
Window.Open; |
| 134 |
|
| 135 |
{ call ApplicationProperties._Resume now, after Window.Open, |
| 136 |
to allow RenderLoadingBackground to happen before doing this. |
| 137 |
It's important, since ApplicationProperties._Resume may e.g. reload |
| 138 |
music files, which takes a while. } |
| 139 |
if Application.ResumeScheduled then |
| 140 |
begin |
| 141 |
ApplicationProperties._Resume; |
| 142 |
Application.ResumeScheduled := false; |
| 143 |
end; |
| 144 |
end; |
| 145 |
|
| 146 |
{ Whenever the context is lost, this is called. |
| 147 |
It's important that we release all OpenGL resources, to recreate them later. } |
| 148 |
procedure CloseContext; |
| 149 |
var |
| 150 |
Window: TCastleWindow; |
| 151 |
begin |
| 152 |
AndroidLog(alInfo, 'CloseContext'); |
| 153 |
|
| 154 |
Window := Application.MainWindow; |
| 155 |
if Window <> nil then |
| 156 |
begin |
| 157 |
{ Passing QuitWhenLastWindowClosed = false here is critical: |
| 158 |
|
| 159 |
Window may be closed and reopened during Android application lifetime, |
| 160 |
this is normal e.g. on low-end Android devices that need to close |
| 161 |
OpenGLES context (stopping activity) when switching to another application. |
| 162 |
CGE handles it gracefully by allowing to open the TCastleWindow again |
| 163 |
(creating OpenGL context). |
| 164 |
Pascal code (like current TCastleView and its state) retains full |
| 165 |
knowledge about the current state, so it generally restarts where it |
| 166 |
left off. |
| 167 |
|
| 168 |
Testcase: platformer, on Android, go to "Credits" and click on some |
| 169 |
link to open the browser. |
| 170 |
Do it on low-end Android device (e.g. Samsung Galaxy Tab A). } |
| 171 |
Window.Close(false); |
| 172 |
|
| 173 |
Window.NativeWindow := nil; // make sure to not access the NativeWindow anymore |
| 174 |
end; |
| 175 |
end; |
| 176 |
|
| 177 |
function DetermineDpi(App: PAndroid_app): Single; |
| 178 |
type |
| 179 |
TAConfiguration_getScreenHeightDp = function (config: PAConfiguration): cint32; cdecl; |
| 180 |
var |
| 181 |
ScreenHeightDp: Integer; |
| 182 |
AndroidLibrary: TDynLib; |
| 183 |
AConfiguration_getScreenHeightDp: TAConfiguration_getScreenHeightDp; |
| 184 |
Dpi: Single; |
| 185 |
begin |
| 186 |
Dpi := 0; |
| 187 |
|
| 188 |
// function to retreive precise DPI is in a newer NDK, let's load it dynamically |
| 189 |
AndroidLibrary := TDynLib.Load(CastleAndroidInternalConfiguration.LibName, false); |
| 190 |
if Assigned(AndroidLibrary) then |
| 191 |
begin |
| 192 |
AndroidLibrary.SymbolError := seReturnNil; |
| 193 |
AConfiguration_getScreenHeightDp := TAConfiguration_getScreenHeightDp(AndroidLibrary.Symbol('AConfiguration_getScreenHeightDp')); |
| 194 |
if Assigned(AConfiguration_getScreenHeightDp) then |
| 195 |
begin |
| 196 |
ScreenHeightDp := AConfiguration_getScreenHeightDp(App^.Config); |
| 197 |
if ScreenHeightDp <> 0 {ACONFIGURATION_SCREEN_HEIGHT_DP_ANY} then |
| 198 |
Dpi := (ANativeWindow_getHeight(App^.Window) * DefaultDpi) / ScreenHeightDp; |
| 199 |
end; |
| 200 |
FreeAndNil(AndroidLibrary); |
| 201 |
end; |
| 202 |
|
| 203 |
// when the above function fails, get the rough value |
| 204 |
if Dpi = 0 then |
| 205 |
begin |
| 206 |
Dpi := AConfiguration_getDensity(App^.Config); |
| 207 |
if (Dpi = ACONFIGURATION_DENSITY_DEFAULT) or |
| 208 |
(Dpi = ACONFIGURATION_DENSITY_NONE) then |
| 209 |
Dpi := 0; |
| 210 |
end; |
| 211 |
|
| 212 |
if Dpi > 0 then |
| 213 |
Result := Dpi |
| 214 |
else |
| 215 |
Result := DefaultDpi; |
| 216 |
end; |
| 217 |
|
| 218 |
procedure TCastleApplication.HandleCommand(App: PAndroid_app; Command: Integer); |
| 219 |
var |
| 220 |
QEvent: TQueuedEvent; |
| 221 |
{$ifdef CASTLE_PERSISTENT_ANDROID_STATE} |
| 222 |
ConfigState: TStringStream; |
| 223 |
{$endif} |
| 224 |
begin |
| 225 |
case Command of |
| 226 |
APP_CMD_INIT_WINDOW: |
| 227 |
begin |
| 228 |
{ We will actually process this event (calling TCastleWindow.Open) |
| 229 |
later, to avoid ANRs when OnOpen does something time-consuming. } |
| 230 |
MainWindow.NativeWindow := App^.Window; |
| 231 |
MainWindow.Container.Dpi := DetermineDpi(App); |
| 232 |
QEvent.EventType := aeOpen; |
| 233 |
QEvents.Add(QEvent); |
| 234 |
end; |
| 235 |
APP_CMD_TERM_WINDOW: |
| 236 |
begin |
| 237 |
{ Note that we cannot delay processing this event using |
| 238 |
QEvents. After CloseContext, window is really destroyed, |
| 239 |
see android_app_post_exec_cmd in native app glue. } |
| 240 |
QEvents.Clear; |
| 241 |
CloseContext; |
| 242 |
end; |
| 243 |
{$ifdef CASTLE_PERSISTENT_ANDROID_STATE} |
| 244 |
APP_CMD_SAVE_STATE: |
| 245 |
begin |
| 246 |
{ We cannot delay processing this, onSaveInstanceState waits for us |
| 247 |
to fill App^.SavedState. } |
| 248 |
ConfigState := TStringStream.Create(''); |
| 249 |
try |
| 250 |
{ read Config to ConfigState } |
| 251 |
Config.Save(ConfigState); |
| 252 |
ConfigState.Position := 0; |
| 253 |
{ read ConfigState to App^.SavedState } |
| 254 |
App^.SavedState := AllocateSavedState(ConfigState.Size); |
| 255 |
ConfigState.ReadBuffer(App^.SavedState^, ConfigState.Size); |
| 256 |
App^.SavedStateSize := ConfigState.Size; |
| 257 |
{ log } |
| 258 |
WritelnLogMultiline('Config', 'Saved state:' + NL + ConfigState.DataString); |
| 259 |
finally FreeAndNil(ConfigState) end; |
| 260 |
end; |
| 261 |
{$endif CASTLE_PERSISTENT_ANDROID_STATE} |
| 262 |
APP_CMD_PAUSE : ApplicationProperties._Pause; |
| 263 |
APP_CMD_RESUME: |
| 264 |
{ In some cases context is not destroyed, so ContextOpen will not be called. |
| 265 |
In those cases we need only call _Resume. |
| 266 |
Test case: share button click and return to app. } |
| 267 |
if (Application.MainWindow <> nil) and (Application.MainWindow.NativeWindow <> nil) then |
| 268 |
ApplicationProperties._Resume |
| 269 |
else |
| 270 |
ResumeScheduled := true; |
| 271 |
end; |
| 272 |
end; |
| 273 |
|
| 274 |
function TCastleApplication.HandleInput(App: PAndroid_app; Event: PAInputEvent): boolean; |
| 275 |
|
| 276 |
function CurrentPosition(const PointerIndex: Integer): TVector2; |
| 277 |
begin |
| 278 |
// TODO: Use LeftTopToCastle, test |
| 279 |
// (It should be OK, since ScreenHeight should equal FRealHeight always) |
| 280 |
Result := Vector2( |
| 281 |
AMotionEvent_getX(Event, PointerIndex), |
| 282 |
ScreenHeight - AMotionEvent_getY(Event, PointerIndex)); |
| 283 |
end; |
| 284 |
|
| 285 |
{ Note that MotionDown etc. do *not* call directly DoMouseDown and similar, |
| 286 |
as we *cannot* block HandleInput for indefinite amount of time |
| 287 |
(and DoMouseDown may call OnPress which may even do MessageOK |
| 288 |
that makes a modal dialog calling Application.ProcessMessage inside). |
| 289 |
The API of native_app_glue is somewhat stupid, it allows us to process |
| 290 |
messages in a loop, but still the HandleInput and HandleCommand |
| 291 |
cannot block making a modal dialog --- the process_input and process_cmd |
| 292 |
implementations in native_app_glue depend on that. } |
| 293 |
|
| 294 |
procedure MotionDown(const FingerIndex: TFingerIndex; const PointerIndex: Integer); |
| 295 |
var |
| 296 |
QEvent: TQueuedEvent; |
| 297 |
begin |
| 298 |
if FingerIndex < FingerCount then |
| 299 |
begin |
| 300 |
{ update TouchChanges } |
| 301 |
TouchChanges[FingerIndex].OldPosition := TouchChanges[FingerIndex].Position; |
| 302 |
TouchChanges[FingerIndex].Position := CurrentPosition(PointerIndex); |
| 303 |
|
| 304 |
QEvent.EventType := aeMotionDown; |
| 305 |
QEvent.FingerIndex := FingerIndex; |
| 306 |
QEvent.Touch := TouchChanges[FingerIndex]; |
| 307 |
QEvents.Add(QEvent); |
| 308 |
end; |
| 309 |
end; |
| 310 |
|
| 311 |
procedure MotionUp(const FingerIndex: TFingerIndex; const PointerIndex: Integer); |
| 312 |
var |
| 313 |
QEvent: TQueuedEvent; |
| 314 |
begin |
| 315 |
if FingerIndex < FingerCount then |
| 316 |
begin |
| 317 |
{ update TouchChanges } |
| 318 |
TouchChanges[FingerIndex].OldPosition := TouchChanges[FingerIndex].Position; |
| 319 |
TouchChanges[FingerIndex].Position := CurrentPosition(PointerIndex); |
| 320 |
|
| 321 |
QEvent.EventType := aeMotionUp; |
| 322 |
QEvent.FingerIndex := FingerIndex; |
| 323 |
QEvent.Touch := TouchChanges[FingerIndex]; |
| 324 |
QEvents.Add(QEvent); |
| 325 |
end; |
| 326 |
end; |
| 327 |
|
| 328 |
procedure MotionMove(const FingerIndex: TFingerIndex; const PointerIndex: Integer); |
| 329 |
var |
| 330 |
QEvent: TQueuedEvent; |
| 331 |
NewPosition: TVector2; |
| 332 |
const |
| 333 |
MinDistanceToReportMove = 0.5; |
| 334 |
begin |
| 335 |
if FingerIndex < FingerCount then |
| 336 |
begin |
| 337 |
NewPosition := CurrentPosition(PointerIndex); |
| 338 |
if PointsDistanceSqr(NewPosition, TouchChanges[FingerIndex].Position) > |
| 339 |
Sqr(MinDistanceToReportMove) then |
| 340 |
begin |
| 341 |
{ update TouchChanges } |
| 342 |
TouchChanges[FingerIndex].OldPosition := TouchChanges[FingerIndex].Position; |
| 343 |
TouchChanges[FingerIndex].Position := NewPosition; |
| 344 |
|
| 345 |
QEvent.EventType := aeMotionMove; |
| 346 |
QEvent.FingerIndex := FingerIndex; |
| 347 |
QEvent.Touch := TouchChanges[FingerIndex]; |
| 348 |
QEvents.Add(QEvent); |
| 349 |
end; |
| 350 |
end; |
| 351 |
end; |
| 352 |
|
| 353 |
var |
| 354 |
MotionAction, PointerIndex, ActionPointerIndex: Integer; |
| 355 |
begin |
| 356 |
Result := false; |
| 357 |
if AInputEvent_getType(Event) = AINPUT_EVENT_TYPE_MOTION then |
| 358 |
begin |
| 359 |
MotionAction := AMotionEvent_getAction(Event) and AMOTION_EVENT_ACTION_MASK; |
| 360 |
ActionPointerIndex := (AMotionEvent_getAction(Event) and |
| 361 |
AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) shr |
| 362 |
AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; |
| 363 |
|
| 364 |
case MotionAction of |
| 365 |
AMOTION_EVENT_ACTION_DOWN: |
| 366 |
begin |
| 367 |
for PointerIndex := 0 to AMotionEvent_getPointerCount(Event) - 1 do |
| 368 |
MotionDown(AMotionEvent_getPointerId(Event, PointerIndex), PointerIndex); |
| 369 |
Result := true; |
| 370 |
end; |
| 371 |
AMOTION_EVENT_ACTION_UP: |
| 372 |
begin |
| 373 |
for PointerIndex := 0 to AMotionEvent_getPointerCount(Event) - 1 do |
| 374 |
MotionUp(AMotionEvent_getPointerId(Event, PointerIndex), PointerIndex); |
| 375 |
Result := true; |
| 376 |
end; |
| 377 |
AMOTION_EVENT_ACTION_CANCEL: |
| 378 |
WritelnLog('Android', 'Motion cancel event'); |
| 379 |
{ TODO: Handle this like AMOTION_EVENT_ACTION_UP? } |
| 380 |
AMOTION_EVENT_ACTION_POINTER_DOWN: |
| 381 |
MotionDown(AMotionEvent_getPointerId(Event, ActionPointerIndex), ActionPointerIndex); |
| 382 |
AMOTION_EVENT_ACTION_POINTER_UP: |
| 383 |
MotionUp(AMotionEvent_getPointerId(Event, ActionPointerIndex), ActionPointerIndex); |
| 384 |
AMOTION_EVENT_ACTION_MOVE: |
| 385 |
begin |
| 386 |
for PointerIndex := 0 to AMotionEvent_getPointerCount(Event) - 1 do |
| 387 |
MotionMove(AMotionEvent_getPointerId(Event, PointerIndex), PointerIndex); |
| 388 |
Result := true; |
| 389 |
end; |
| 390 |
end; |
| 391 |
end; |
| 392 |
end; |
| 393 |
|
| 394 |
procedure AndroidMainImplementation(App: PAndroid_App); |
| 395 |
|
| 396 |
function GetInternalDataPath: String; |
| 397 |
var |
| 398 |
Env: PJNIEnv; |
| 399 |
|
| 400 |
activityClass: jclass; |
| 401 |
getFilesDir: jmethodID; |
| 402 |
fileObject: jobject; |
| 403 |
|
| 404 |
fileClass: jclass; |
| 405 |
getAbsolutePath: jmethodID; |
| 406 |
pathObject: jobject; |
| 407 |
|
| 408 |
ResultStr: PChar; |
| 409 |
Dummy: JBoolean; |
| 410 |
begin |
| 411 |
if App^.Activity^.InternalDataPath <> nil then |
| 412 |
Result := App^.Activity^.InternalDataPath else // this is the usual route |
| 413 |
{ On Android 2.3.x, above is unfortunately broken. |
| 414 |
So get internal data path manually, see |
| 415 |
http://stackoverflow.com/questions/10683119/android-app-activity-internaldatapath-still-null-in-2-3-8-ndk-r8 |
| 416 |
https://groups.google.com/forum/#!topic/android-ndk/4lD8OS-w4UU } |
| 417 |
begin |
| 418 |
Env := nil; // make sure uninitialized |
| 419 |
|
| 420 |
{ you need to get Env this way, not from App^.Activity^.Env, |
| 421 |
otherwise fileClass := Env^^.GetObjectClass will crash with segfault. } |
| 422 |
App^.Activity^.VM^^.AttachCurrentThread(App^.Activity^.VM, @Env, nil); |
| 423 |
|
| 424 |
activityClass := Env^^.GetObjectClass(Env, app^.activity^.clazz); |
| 425 |
getFilesDir := Env^^.GetMethodID(Env, activityClass, 'getFilesDir', '()Ljava/io/File;'); |
| 426 |
fileObject := Env^^.CallObjectMethod(Env, app^.activity^.clazz, getFilesDir); |
| 427 |
|
| 428 |
fileClass := Env^^.GetObjectClass(Env, fileObject); |
| 429 |
getAbsolutePath := Env^^.GetMethodID(Env, fileClass, 'getAbsolutePath', '()Ljava/lang/String;'); |
| 430 |
pathObject := Env^^.CallObjectMethod(Env, fileObject, getAbsolutePath); |
| 431 |
|
| 432 |
Dummy := 0; |
| 433 |
ResultStr := Env^^.GetStringUTFChars(Env, jstring(pathObject), |
| 434 |
{$ifdef VER2} Dummy {$else} @Dummy {$endif}); |
| 435 |
|
| 436 |
Result := AnsiString(ResultStr); // will copy characters |
| 437 |
|
| 438 |
Env^^.DeleteLocalRef(Env, pathObject); |
| 439 |
Env^^.DeleteLocalRef(Env, fileClass); |
| 440 |
Env^^.DeleteLocalRef(Env, fileObject); |
| 441 |
Env^^.DeleteLocalRef(Env, activityClass); |
| 442 |
|
| 443 |
Env^^.ReleaseStringUTFChars(Env, jstring(pathObject), ResultStr); |
| 444 |
|
| 445 |
App^.Activity^.VM^^.DetachCurrentThread(App^.Activity^.VM); |
| 446 |
end; |
| 447 |
end; |
| 448 |
|
| 449 |
{$ifdef CASTLE_PERSISTENT_ANDROID_STATE} |
| 450 |
var |
| 451 |
ConfigState: TStringStream; |
| 452 |
{$endif CASTLE_PERSISTENT_ANDROID_STATE} |
| 453 |
begin |
| 454 |
ApplicationConfigOverride := FilenameToUriSafe(InclPathDelim(GetInternalDataPath)); |
| 455 |
|
| 456 |
{$ifdef CASTLE_PERSISTENT_ANDROID_STATE} |
| 457 |
{ Use SavedState as XML contents that should be loaded to global Config. |
| 458 |
Note that we directly use AndroidLog below, not WritelnLog or WritelnWarning, |
| 459 |
because user code had no chance to call InitializeLog yet. } |
| 460 |
if App^.SavedState <> nil then |
| 461 |
begin |
| 462 |
ConfigState := TStringStream.Create(''); |
| 463 |
try |
| 464 |
{ load ConfigState from App^.SavedState } |
| 465 |
ConfigState.WriteBuffer(App^.SavedState^, App^.SavedStateSize); |
| 466 |
ConfigState.Position := 0; |
| 467 |
{ load Config from ConfigState } |
| 468 |
try |
| 469 |
Config.Load(ConfigState); |
| 470 |
{ log } |
| 471 |
AndroidLog(alInfo, 'Config: Loaded state:' + NL + ConfigState.DataString); |
| 472 |
except |
| 473 |
on E: TObject do |
| 474 |
AndroidLog(alWarn, 'Config: Cannot read XML config from Android state: ' + ExceptMessage(E)); |
| 475 |
end; |
| 476 |
finally FreeAndNil(ConfigState) end; |
| 477 |
end else |
| 478 |
AndroidLog(alInfo, 'Config: no saved state'); |
| 479 |
{$endif CASTLE_PERSISTENT_ANDROID_STATE} |
| 480 |
|
| 481 |
Application.Run; |
| 482 |
end; |
| 483 |
|
| 484 |
{ TCastleWindow ---------------------------------------------------------- } |
| 485 |
|
| 486 |
procedure TCastleWindow.CreateBackend; |
| 487 |
begin |
| 488 |
Messaging.OnReceive.Add({$ifdef FPC}@{$endif}HandleOnScreenKeyboard); |
| 489 |
end; |
| 490 |
|
| 491 |
function TCastleWindow.HandleOnScreenKeyboard(const Received: TCastleStringList; |
| 492 |
const ReceivedStream: TMemoryStream): boolean; |
| 493 |
var |
| 494 |
KeyCode: Integer; |
| 495 |
KeyString: String; |
| 496 |
UserInterface: TCastleUserInterface; |
| 497 |
begin |
| 498 |
if (Received.Count = 3) and (Received[0] = 'castle-key-down') then |
| 499 |
begin |
| 500 |
// WritelnLog('key down - code ' + Received[1]); |
| 501 |
// WritelnLog('key down - ' + Received[2]); |
| 502 |
if TryStrToInt(Received[1], KeyCode) then |
| 503 |
begin |
| 504 |
KeyString := Received[2]; |
| 505 |
DoKeyDown(AndroidKeyCodeToKey(KeyCode), KeyString); |
| 506 |
// WritelnLog('was DoKeyDown'); |
| 507 |
end; |
| 508 |
Exit(true); |
| 509 |
end; |
| 510 |
|
| 511 |
if (Received.Count = 3) and (Received[0] = 'castle-key-up') then |
| 512 |
begin |
| 513 |
// WritelnLog('key up - code ' + Received[1]); |
| 514 |
// WritelnLog('key up - ' + Received[2]); |
| 515 |
|
| 516 |
if TryStrToInt(Received[1], KeyCode) then |
| 517 |
begin |
| 518 |
DoKeyUp(AndroidKeyCodeToKey(KeyCode)); |
| 519 |
// WritelnLog('was DoKeyUp'); |
| 520 |
end; |
| 521 |
Exit(true); |
| 522 |
end; |
| 523 |
|
| 524 |
{ Remove ForceCaptureInput when keyboard was closed from java code } |
| 525 |
if (Received.Count = 1) and |
| 526 |
(Received[0] = 'castle-keyboard-hide-remove-force-capture-input') then |
| 527 |
begin |
| 528 |
UserInterface := Container.ForceCaptureInput; |
| 529 |
Container.ForceCaptureInput := nil; |
| 530 |
if UserInterface <> nil then |
| 531 |
UserInterface.Focused := false; |
| 532 |
|
| 533 |
WritelnLog('castle-keyboard-hide-remove-force-capture-input'); |
| 534 |
Exit(true); |
| 535 |
end; |
| 536 |
end; |
| 537 |
|
| 538 |
function TCastleWindow.AndroidKeyCodeToKey(const AndroidKeyCode: Integer): TKey; |
| 539 |
begin |
| 540 |
// http://www.temblast.com/ref/akeyscode.htm |
| 541 |
case AndroidKeyCode of |
| 542 |
0: Result := keyNone; |
| 543 |
1: Result := keyArrowLeft; |
| 544 |
2: Result := keyArrowRight; |
| 545 |
3: Result := keyHome; |
| 546 |
4: Result := keyEnd; |
| 547 |
|
| 548 |
7: Result := key0; |
| 549 |
8: Result := key1; |
| 550 |
9: Result := key2; |
| 551 |
10: Result := key3; |
| 552 |
11: Result := key4; |
| 553 |
12: Result := key5; |
| 554 |
13: Result := key6; |
| 555 |
14: Result := key7; |
| 556 |
15: Result := key8; |
| 557 |
16: Result := key9; |
| 558 |
|
| 559 |
17: Result := key8; // keyStar in android - we use simply key8 |
| 560 |
|
| 561 |
29: Result := keyA; |
| 562 |
30: Result := keyB; |
| 563 |
31: Result := keyC; |
| 564 |
32: Result := keyD; |
| 565 |
33: Result := keyE; |
| 566 |
34: Result := keyF; |
| 567 |
35: Result := keyG; |
| 568 |
36: Result := keyH; |
| 569 |
37: Result := keyI; |
| 570 |
38: Result := keyJ; |
| 571 |
39: Result := keyK; |
| 572 |
40: Result := keyL; |
| 573 |
41: Result := keyM; |
| 574 |
42: Result := keyN; |
| 575 |
43: Result := keyO; |
| 576 |
44: Result := keyP; |
| 577 |
45: Result := keyQ; |
| 578 |
46: Result := keyR; |
| 579 |
47: Result := keyS; |
| 580 |
48: Result := keyT; |
| 581 |
49: Result := keyU; |
| 582 |
50: Result := keyV; |
| 583 |
51: Result := keyW; |
| 584 |
52: Result := keyX; |
| 585 |
53: Result := keyY; |
| 586 |
54: Result := keyZ; |
| 587 |
|
| 588 |
55: Result := keyComma; |
| 589 |
56: Result := keyPeriod; |
| 590 |
|
| 591 |
61: Result := keyTab; |
| 592 |
62: Result := keySpace; |
| 593 |
66: Result := keyEnter; |
| 594 |
67: Result := keyBackSpace; |
| 595 |
68: Result := keyBackQuote; |
| 596 |
69: Result := keyMinus; |
| 597 |
70: Result := keyEqual; |
| 598 |
71: Result := keyLeftBracket; |
| 599 |
72: Result := keyRightBracket; |
| 600 |
73: Result := keyBackSlash; |
| 601 |
74: Result := keySemicolon; |
| 602 |
75: Result := keyApostrophe; |
| 603 |
76: Result := keySlash; |
| 604 |
77: Result := key2; // keyAt in android we use simply 2 |
| 605 |
81: Result := keyPlus; |
| 606 |
|
| 607 |
else Result := keyNone; |
| 608 |
end; |
| 609 |
end; |
| 610 |
|
| 611 |
{ It would be nice to update Android's app menu based on MainMenu contents. |
| 612 |
But we cannot do this from NDK, it would require implementing Java code |
| 613 |
connected to us. } |
| 614 |
|
| 615 |
procedure TCastleWindow.BackendMenuInitialize; |
| 616 |
begin |
| 617 |
end; |
| 618 |
|
| 619 |
procedure TCastleWindow.BackendMenuFinalize; |
| 620 |
begin |
| 621 |
end; |
| 622 |
|
| 623 |
procedure TCastleWindow.MenuUpdateCaption(Entry: TMenuEntryWithCaption); |
| 624 |
begin |
| 625 |
MenuFinalize; |
| 626 |
MenuInitialize; |
| 627 |
end; |
| 628 |
|
| 629 |
procedure TCastleWindow.MenuUpdateEnabled(Entry: TMenuEntryWithCaption); |
| 630 |
begin |
| 631 |
MenuFinalize; |
| 632 |
MenuInitialize; |
| 633 |
end; |
| 634 |
|
| 635 |
procedure TCastleWindow.MenuUpdateChecked(Entry: TMenuItemChecked); |
| 636 |
begin |
| 637 |
MenuFinalize; |
| 638 |
MenuInitialize; |
| 639 |
end; |
| 640 |
|
| 641 |
function TCastleWindow.MenuUpdateCheckedFast: boolean; |
| 642 |
begin |
| 643 |
Result := false; |
| 644 |
end; |
| 645 |
|
| 646 |
procedure TCastleWindow.MenuInsert(const Parent: TMenu; |
| 647 |
const ParentPosition: Integer; const Entry: TMenuEntry); |
| 648 |
begin |
| 649 |
MenuFinalize; |
| 650 |
MenuInitialize; |
| 651 |
end; |
| 652 |
|
| 653 |
procedure TCastleWindow.MenuDelete(const Parent: TMenu; |
| 654 |
const ParentPosition: Integer; const Entry: TMenuEntry); |
| 655 |
begin |
| 656 |
MenuFinalize; |
| 657 |
MenuInitialize; |
| 658 |
end; |
| 659 |
|
| 660 |
procedure TCastleWindow.OpenBackend; |
| 661 |
begin |
| 662 |
ContextCreate(NativeWindow); |
| 663 |
Application.OpenWindowsAdd(Self); |
| 664 |
end; |
| 665 |
|
| 666 |
procedure TCastleWindow.CloseBackend; |
| 667 |
begin |
| 668 |
ContextDestroy; |
| 669 |
{ Note that we do not clear NativeWindow now, because we may need it |
| 670 |
if window is opened again. Although when Android system opens the window, |
| 671 |
NativeWindow is set by OpenContext, |
| 672 |
but when we manually reopen the window from |
| 673 |
code (like "reopen context" button in android_demo), we need to keep |
| 674 |
previous NativeWindow value. } |
| 675 |
end; |
| 676 |
|
| 677 |
procedure TCastleWindow.SetCaption(const Part: TCaptionPart; const Value: String); |
| 678 |
begin |
| 679 |
FCaption[Part] := Value; |
| 680 |
// GetWholeCaption is ignored on Android |
| 681 |
end; |
| 682 |
|
| 683 |
procedure TCastleWindow.SetCursor(const Value: TMouseCursor); |
| 684 |
begin |
| 685 |
if FCursor <> Value then |
| 686 |
begin |
| 687 |
FCursor := Value; |
| 688 |
// Cursor is ignored on Android |
| 689 |
end; |
| 690 |
end; |
| 691 |
|
| 692 |
function TCastleWindow.RedirectKeyDownToMenuClick: boolean; |
| 693 |
begin |
| 694 |
{ Call menu shortcuts on key presses. |
| 695 |
Since we don't show MainMenu, this is the only way how we can at least |
| 696 |
support it's shortcuts. } |
| 697 |
Result := true; |
| 698 |
end; |
| 699 |
|
| 700 |
procedure TCastleWindow.SetMousePosition(const Value: TVector2); |
| 701 |
begin |
| 702 |
{ There is no cursor position on Android devices. |
| 703 |
Just update MousePosition (although we're not really required to |
| 704 |
do this, code using SetMousePosition should not depend that |
| 705 |
it was always successful). } |
| 706 |
if not Closed then |
| 707 |
FMousePosition := Value; |
| 708 |
end; |
| 709 |
|
| 710 |
procedure TCastleWindow.UpdateFullScreenBackend; |
| 711 |
begin |
| 712 |
FFullScreenBackend := FFullScreenWanted; // does nothing on Android |
| 713 |
end; |
| 714 |
|
| 715 |
procedure TCastleWindow.BackendInsideUpdate; |
| 716 |
begin |
| 717 |
end; |
| 718 |
|
| 719 |
{ TCastleApplication ---------------------------------------------------------- } |
| 720 |
|
| 721 |
procedure TCastleApplication.CreateBackend; |
| 722 |
begin |
| 723 |
AndroidMain := @AndroidMainImplementation; |
| 724 |
end; |
| 725 |
|
| 726 |
procedure TCastleApplication.DestroyBackend; |
| 727 |
begin |
| 728 |
end; |
| 729 |
|
| 730 |
function TCastleApplication.ProcessAllMessages: boolean; |
| 731 |
begin |
| 732 |
Result := ProcessMessage(false, false); |
| 733 |
end; |
| 734 |
|
| 735 |
function TCastleApplication.ProcessMessage(WaitForMessage, WaitToLimitFPS: boolean): boolean; |
| 736 |
|
| 737 |
{ Call Update on ApplicationProperties and all open Windows. } |
| 738 |
procedure UpdateEverything; |
| 739 |
begin |
| 740 |
ApplicationProperties._Update; |
| 741 |
FOpenWindows.DoUpdate; |
| 742 |
ApplicationProperties._UpdateEnd; |
| 743 |
end; |
| 744 |
|
| 745 |
procedure Resize(Width, Height: Integer); |
| 746 |
begin |
| 747 |
AndroidLog(alInfo, 'Resize (size: %d %d)', [Width, Height]); |
| 748 |
|
| 749 |
FScreenWidth := Width; |
| 750 |
FScreenHeight := Height; |
| 751 |
|
| 752 |
if not MainWindow.Closed then |
| 753 |
MainWindow.DoResize(Width, Height, false); |
| 754 |
end; |
| 755 |
|
| 756 |
var |
| 757 |
Ident, Events, NewWidth, NewHeight: Integer; |
| 758 |
Source: Pandroid_poll_source; |
| 759 |
QEvent: TQueuedEvent; |
| 760 |
MessageHandlingBegin: TTimerResult; |
| 761 |
begin |
| 762 |
MessageHandlingBegin := Timer; |
| 763 |
repeat |
| 764 |
{ When the window is open: We cannot suspend (wait indefinitely for a message) |
| 765 |
an open window, even when AllowSuspendForInput or WaitForMessage. |
| 766 |
That's because we would not react to resize events soon enough then, |
| 767 |
since we have to actually do a couple of loop passes until "resize" event |
| 768 |
reaches us. Reproducible on drawing_toy. |
| 769 |
|
| 770 |
When the window is closed: We can and should suspend in this case, |
| 771 |
regardless of AllowSuspendForInput or WaitForMessage, |
| 772 |
to not waste battery. } |
| 773 |
if (MainWindow = nil) or MainWindow.Closed then |
| 774 |
begin |
| 775 |
WritelnLog('Android', 'Waiting for next event without consuming CPU ticks.'); |
| 776 |
Ident := ALooper_pollAll(-1 { wait }, nil, @Events, @Source); |
| 777 |
end else |
| 778 |
begin |
| 779 |
Ident := ALooper_pollAll(0, nil, @Events, @Source); |
| 780 |
{ Uncomment it to test loop suspending solution. } |
| 781 |
//WritelnLog('Android', 'Looping...'); |
| 782 |
end; |
| 783 |
if Ident < 0 then Break; |
| 784 |
|
| 785 |
if Source <> nil then |
| 786 |
Source^.Process(AndroidMainApp, Source); |
| 787 |
|
| 788 |
{ poll our own events quueue. |
| 789 |
Yes, we need our own events queue to shield from the native_app_glue |
| 790 |
weirdness... } |
| 791 |
if MainWindow <> nil then |
| 792 |
while QEvents.Count > 0 do |
| 793 |
begin |
| 794 |
QEvent := QEvents.First; |
| 795 |
QEvents.Delete(0); |
| 796 |
case QEvent.EventType of |
| 797 |
aeOpen: OpenContext; |
| 798 |
aeMotionDown: |
| 799 |
if not MainWindow.Closed then |
| 800 |
MainWindow.DoMouseDown(QEvent.Touch.Position, buttonLeft, QEvent.FingerIndex); |
| 801 |
aeMotionUp : |
| 802 |
if not MainWindow.Closed then |
| 803 |
MainWindow.DoMouseUp (QEvent.Touch.Position, buttonLeft, QEvent.FingerIndex, false); |
| 804 |
aeMotionMove: |
| 805 |
if not MainWindow.Closed then |
| 806 |
MainWindow.DoMotion (InputMotion(QEvent.Touch.OldPosition, QEvent.Touch.Position, [buttonLeft], QEvent.FingerIndex)); |
| 807 |
end; |
| 808 |
end; |
| 809 |
|
| 810 |
// Check if we are exiting. |
| 811 |
if AndroidMainApp^.DestroyRequested = 1 then |
| 812 |
begin |
| 813 |
CloseContext; |
| 814 |
Terminate; // tell ancestor TCustomApplication to end our loop |
| 815 |
{ The result of ProcessMessage must always be "not Terminated" |
| 816 |
to work with TCustomApplication correctly. |
| 817 |
In this case we know it's "false", since we called "Terminate" above. } |
| 818 |
Exit(not Terminated); |
| 819 |
end; |
| 820 |
|
| 821 |
// loop condition avoids being clogged with motion events |
| 822 |
until TimerSeconds(Timer, MessageHandlingBegin) > |
| 823 |
1 / ApplicationProperties.LimitFPS; |
| 824 |
|
| 825 |
if (MainWindow <> nil) and not MainWindow.Closed then |
| 826 |
begin |
| 827 |
{ Check for Resize. As there is no reliable event to capture it |
| 828 |
(ANativeWindow_getWidth and ANativeWindow_getheight are immediately |
| 829 |
updated, but for some time EGL sizes stay old) so we just watch |
| 830 |
for changes, and only fire our "Resize" when really EGL size changed. |
| 831 |
|
| 832 |
Note that we compare with window FRealWidth/Heigth, not Width/Height. |
| 833 |
Otherwise the window with ResizeAllowed = raOnlyAtOpen would behave |
| 834 |
like it never received previous DoResize. |
| 835 |
} |
| 836 |
MainWindow.QuerySize(NewWidth, NewHeight); |
| 837 |
if (NewWidth <> MainWindow.FRealWidth) or |
| 838 |
(NewHeight <> MainWindow.FRealHeight) then |
| 839 |
Resize(NewWidth, NewHeight); |
| 840 |
|
| 841 |
{ we do not check Invalidated here, just redraw every frame when window is open } |
| 842 |
MainWindow.DoRender; |
| 843 |
|
| 844 |
UpdateEverything; |
| 845 |
end; |
| 846 |
|
| 847 |
{ Note that we ignore WaitToLimitFPS here, right now. |
| 848 |
When the window is open, it is always "on" in the main loop, |
| 849 |
we don't control it, Android throttles render speed anyway. |
| 850 |
When the window is closed, we always wait for message to conserve battery. } |
| 851 |
|
| 852 |
{ the result of ProcessMessage must always be "not Terminated" |
| 853 |
to work with TCustomApplication correctly. } |
| 854 |
Result := not Terminated; |
| 855 |
end; |
| 856 |
|
| 857 |
procedure TCastleApplication.Run; |
| 858 |
begin |
| 859 |
if MainWindow = nil then |
| 860 |
raise Exception.Create('For Android, you have to assign Application.MainWindow'); |
| 861 |
|
| 862 |
if QEvents = nil then |
| 863 |
QEvents := TQueuedEventList.Create else |
| 864 |
QEvents.Clear; |
| 865 |
|
| 866 |
FillByte(TouchChanges, SizeOf(TouchChanges), 0); |
| 867 |
|
| 868 |
{ since we have AndroidMainApp now, prepare it } |
| 869 |
AndroidMainApp^.OnAppCmd := @HandleCommand; |
| 870 |
AndroidMainApp^.OnInputEvent := @HandleInput; |
| 871 |
|
| 872 |
{ We could not do dlopen on Android before AndroidMain is called. |
| 873 |
Load necessary libraries now. Some of the below libraries are not really |
| 874 |
available on Android anyway, but we keep the list below for completeness |
| 875 |
(engine gracefully handles lack of most libraries, only OpenGLES |
| 876 |
is really required). } |
| 877 |
{ Note that this may be called many times, because AndroidMainImplementation |
| 878 |
may be called many times, because ANativeActivity_onCreate may be called |
| 879 |
multple times. So things below must be implemented in a secure way, |
| 880 |
to work Ok when executed multiple times. } |
| 881 |
if not EglAvailable then |
| 882 |
LoadEgl; |
| 883 |
GLESInitialization; |
| 884 |
OpenALInitialization; |
| 885 |
VorbisFileInitialization; |
| 886 |
InitializeAndroidCWString; |
| 887 |
LoadFreeTypeLibrary; |
| 888 |
{$ifdef CASTLE_PNG_DYNAMIC} |
| 889 |
PngInitialization; |
| 890 |
{$endif} |
| 891 |
{$ifndef CASTLE_ZLIB_USING_PASZLIB} |
| 892 |
ZLibInitialization; |
| 893 |
{$endif} |
| 894 |
|
| 895 |
{ this is called by Android activity onCreate, so Java activity |
| 896 |
was recreated } |
| 897 |
InitializedJavaActivity := false; |
| 898 |
|
| 899 |
inherited Initialize; // set Terminated := false |
| 900 |
inherited Run; // calls DoRun, surrounded by HandleException, in a loop |
| 901 |
|
| 902 |
FreeAndNil(QEvents); |
| 903 |
end; |
| 904 |
|
| 905 |
procedure TCastleApplication.BackendTerminate; |
| 906 |
begin |
| 907 |
end; |
| 908 |
|
| 909 |
function TCastleApplication.ScreenWidth: integer; |
| 910 |
begin |
| 911 |
if FScreenWidth = 0 then |
| 912 |
WritelnWarning('Window', 'Application.ScreenWidth is queried before window is open, returns zero'); |
| 913 |
Result := FScreenWidth; |
| 914 |
end; |
| 915 |
|
| 916 |
function TCastleApplication.ScreenHeight: integer; |
| 917 |
begin |
| 918 |
if FScreenHeight = 0 then |
| 919 |
WritelnWarning('Window', 'Application.ScreenHeight is queried before window is open, returns zero'); |
| 920 |
Result := FScreenHeight; |
| 921 |
end; |
| 922 |
|
| 923 |
function TCastleApplication.BackendName: String; |
| 924 |
begin |
| 925 |
Result := 'Android'; |
| 926 |
end; |
| 927 |
|
| 928 |
{ TWindowContainer ----------------------------------------------------------- } |
| 929 |
|
| 930 |
function TWindowContainer.SettingMousePositionCausesMotion: Boolean; |
| 931 |
begin |
| 932 |
Result := true; |
| 933 |
end; |
| 934 |
|
| 935 |
{$endif read_implementation} |