-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
NativeActivity.java
1624 lines (1465 loc) · 54.9 KB
/
NativeActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.ppsspp.ppsspp;
import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.UiModeManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.ConfigurationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.os.Vibrator;
import android.provider.MediaStore;
import androidx.documentfile.provider.DocumentFile;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.InputDevice;
import android.view.InputEvent;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;
import java.io.File;
import java.lang.reflect.Field;
import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@SuppressWarnings("ConstantConditions")
public abstract class NativeActivity extends Activity {
// Remember to loadLibrary your JNI .so in a static {} block
// Adjust these as necessary
private static final String TAG = "PPSSPPNativeActivity";
// Allows us to skip a lot of initialization on secondary calls to onCreate.
private static boolean initialized = false;
// False to use Vulkan, queried from C++ after NativeApp.init.
private static boolean javaGL = true;
// Graphics and audio interfaces for Vulkan (javaGL = false)
private NativeSurfaceView mSurfaceView;
private Surface mSurface;
// Graphics and audio interfaces for Java EGL (javaGL = true)
private NativeGLView mGLSurfaceView;
protected NativeRenderer nativeRenderer;
private String shortcutParam = "";
private static String overrideShortcutParam = null;
public static String runCommand;
public static String commandParameter;
// Remember settings for best audio latency
private int optimalFramesPerBuffer;
private int optimalSampleRate;
private boolean sustainedPerfSupported;
private View navigationCallbackView = null;
// audioFocusChangeListener to listen to changes in audio state
private AudioFocusChangeListener audioFocusChangeListener;
private AudioManager audioManager;
private PowerManager powerManager;
private Vibrator vibrator;
private boolean isXperiaPlay;
// This is to avoid losing the game/menu state etc when we are just
// switched-away from or rotated etc.
private boolean shuttingDown;
private static final int RESULT_LOAD_IMAGE = 101;
private static final int RESULT_OPEN_DOCUMENT = 102;
private static final int RESULT_OPEN_DOCUMENT_TREE = 103;
// Allow for multiple connected gamepads but just consider them the same for now.
// Actually this is not entirely true, see the code.
private ArrayList<InputDeviceState> inputPlayers = new ArrayList<InputDeviceState>();
private PowerSaveModeReceiver mPowerSaveModeReceiver = null;
private SizeManager sizeManager = null;
private static LocationHelper mLocationHelper;
private static CameraHelper mCameraHelper;
private static final String[] permissionsForStorage = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
};
private static final String[] permissionsForLocation = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
};
private static final String[] permissionsForCamera = {
Manifest.permission.CAMERA
};
private static final String[] permissionsForMicrophone = {
Manifest.permission.RECORD_AUDIO
};
public static final int REQUEST_CODE_STORAGE_PERMISSION = 1;
public static final int REQUEST_CODE_LOCATION_PERMISSION = 2;
public static final int REQUEST_CODE_CAMERA_PERMISSION = 3;
public static final int REQUEST_CODE_MICROPHONE_PERMISSION = 4;
// Functions for the app activity to override to change behaviour.
public native void registerCallbacks();
public native void unregisterCallbacks();
NativeRenderer getRenderer() {
return nativeRenderer;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void detectOptimalAudioSettings() {
try {
optimalFramesPerBuffer = Integer.parseInt(this.audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
} catch (NumberFormatException e) {
// Ignore, if we can't parse it it's bogus and zero is a fine value (means we couldn't detect it).
}
try {
optimalSampleRate = Integer.parseInt(this.audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
} catch (NumberFormatException e) {
// Ignore, if we can't parse it it's bogus and zero is a fine value (means we couldn't detect it).
}
}
String getApplicationLibraryDir(ApplicationInfo application) {
String libdir = null;
try {
// Starting from Android 2.3, nativeLibraryDir is available:
Field field = ApplicationInfo.class.getField("nativeLibraryDir");
libdir = (String) field.get(application);
} catch (SecurityException e1) {
} catch (NoSuchFieldException e1) {
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
}
if (libdir == null) {
// Fallback for Android < 2.3:
libdir = application.dataDir + "/lib";
}
return libdir;
}
@TargetApi(Build.VERSION_CODES.M)
boolean askForPermissions(String[] permissions, int requestCode) {
boolean shouldAsk = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (String permission : permissions) {
if (this.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
shouldAsk = true;
}
}
if (shouldAsk) {
this.requestPermissions(permissions, requestCode);
}
}
return shouldAsk;
}
@TargetApi(Build.VERSION_CODES.M)
public void sendInitialGrants() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Let's start out granted if it was granted already.
if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
NativeApp.sendMessageFromJava("permission_granted", "storage");
} else {
NativeApp.sendMessageFromJava("permission_denied", "storage");
}
}
}
boolean permissionsGranted(String[] permissions, int[] grantResults) {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED)
return false;
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, String [] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_STORAGE_PERMISSION:
if (permissionsGranted(permissions, grantResults)) {
NativeApp.sendMessageFromJava("permission_granted", "storage");
} else {
NativeApp.sendMessageFromJava("permission_denied", "storage");
}
break;
case REQUEST_CODE_LOCATION_PERMISSION:
if (permissionsGranted(permissions, grantResults)) {
mLocationHelper.startLocationUpdates();
}
break;
case REQUEST_CODE_CAMERA_PERMISSION:
if (mCameraHelper != null && permissionsGranted(permissions, grantResults)) {
mCameraHelper.startCamera();
}
break;
case REQUEST_CODE_MICROPHONE_PERMISSION:
if (permissionsGranted(permissions, grantResults)) {
NativeApp.audioRecording_Start();
}
break;
default:
}
}
public void setShortcutParam(String shortcutParam) {
this.shortcutParam = ((shortcutParam == null) ? "" : shortcutParam);
}
// Unofficial hacks to get a list of SD cards that are not the main "external storage".
private static ArrayList<String> getSdCardPaths(final Context context) {
// Q is the last version that will support normal file access.
ArrayList<String> list = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) {
Log.i(TAG, "getSdCardPaths: Trying KitKat method");
list = getSdCardPaths19(context);
}
if (list == null) {
Log.i(TAG, "getSdCardPaths: Attempting fallback");
// Try another method.
String removableStoragePath;
list = new ArrayList<String>();
File fileList[] = new File("/storage/").listFiles();
if (fileList != null) {
for (File file : fileList) {
if (!file.getAbsolutePath().equalsIgnoreCase(Environment.getExternalStorageDirectory().getAbsolutePath()) && file.isDirectory() && file.canRead()) {
list.add(file.getAbsolutePath());
}
}
}
}
if (list == null) {
String[] varNames = { "EXTERNAL_SDCARD_STORAGE", "SECONDARY_STORAGE" };
for (String var : varNames) {
Log.i(TAG, "getSdCardPaths: Checking env " + var);
String secStore = System.getenv("SECONDARY_STORAGE");
if (secStore != null && secStore.length() > 0) {
list = new ArrayList<String>();
list.add(secStore);
break;
}
}
}
if (list == null) {
return new ArrayList<String>();
} else {
return list;
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private static ArrayList<String> getSdCardPaths19(final Context context)
{
final File[] externalCacheDirs = context.getExternalCacheDirs();
if (externalCacheDirs == null || externalCacheDirs.length==0)
return null;
if (externalCacheDirs.length == 1) {
if (externalCacheDirs[0] == null)
return null;
final String storageState = Environment.getStorageState(externalCacheDirs[0]);
if (!Environment.MEDIA_MOUNTED.equals(storageState))
return null;
if (Environment.isExternalStorageEmulated())
return null;
}
final ArrayList<String> result = new ArrayList<>();
if (externalCacheDirs.length == 1)
result.add(getRootOfInnerSdCardFolder(externalCacheDirs[0]));
for (int i = 1; i < externalCacheDirs.length; ++i)
{
final File file = externalCacheDirs[i];
if (file == null)
continue;
final String storageState = Environment.getStorageState(file);
if (Environment.MEDIA_MOUNTED.equals(storageState)) {
String root = getRootOfInnerSdCardFolder(externalCacheDirs[i]);
if (root != null) {
result.add(root);
}
}
}
if (result.isEmpty())
return null;
return result;
}
/** Given any file/folder inside an sd card, this will return the path of the sd card */
private static String getRootOfInnerSdCardFolder(File file)
{
if (file == null)
return null;
final long totalSpace = file.getTotalSpace();
if (totalSpace <= 0) {
return null;
}
while (true) {
final File parentFile = file.getParentFile();
if (parentFile == null || !parentFile.canRead()) {
break;
}
if (parentFile.getTotalSpace() != totalSpace) {
break;
}
file = parentFile;
}
return file.getAbsolutePath();
}
public void Initialize() {
// Initialize audio classes. Do this here since detectOptimalAudioSettings()
// needs audioManager
this.audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
this.audioFocusChangeListener = new AudioFocusChangeListener();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// Get the optimal buffer sz
detectOptimalAudioSettings();
}
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
if (powerManager != null && powerManager.isSustainedPerformanceModeSupported()) {
sustainedPerfSupported = true;
NativeApp.sendMessageFromJava("sustained_perf_supported", "1");
}
}
// isLandscape is used to trigger GetAppInfo currently, we
boolean landscape = NativeApp.isLandscape();
Log.d(TAG, "Landscape: " + landscape);
// Get system information
PackageManager packMgmr = getPackageManager();
String packageName = getPackageName();
ApplicationInfo appInfo;
try {
appInfo = packMgmr.getApplicationInfo(packageName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
int deviceType = NativeApp.DEVICE_TYPE_MOBILE;
if (isVRDevice()) {
deviceType = NativeApp.DEVICE_TYPE_VR;
}
UiModeManager uiModeManager = (UiModeManager) getSystemService(UI_MODE_SERVICE);
switch (uiModeManager.getCurrentModeType()) {
case Configuration.UI_MODE_TYPE_TELEVISION:
deviceType = NativeApp.DEVICE_TYPE_TV;
Log.i(TAG, "Running on an Android TV Device");
break;
case Configuration.UI_MODE_TYPE_DESK:
deviceType = NativeApp.DEVICE_TYPE_DESKTOP;
Log.i(TAG, "Running on an Android desktop computer (!)");
break;
// All other device types are treated the same.
}
isXperiaPlay = IsXperiaPlay();
String extStorageState = Environment.getExternalStorageState();
String extStorageDir = Environment.getExternalStorageDirectory().getAbsolutePath();
File externalFiles = this.getExternalFilesDir(null);
String externalFilesDir = externalFiles == null ? "" : externalFiles.getAbsolutePath();
String nativeLibDir = getApplicationLibraryDir(appInfo);
Log.i(TAG, "Ext storage: " + extStorageState + " " + extStorageDir);
Log.i(TAG, "Ext files dir: " + externalFilesDir);
String additionalStorageDirs = "";
try {
ArrayList<String> sdCards = getSdCardPaths(this);
// String.join doesn't exist on old devices (???).
StringBuilder s = new StringBuilder();
for (int i = 0; i < sdCards.size(); i++) {
String sdCard = sdCards.get(i);
Log.i(TAG, "SD card: " + sdCard);
s.append(sdCard);
if (i != sdCards.size() - 1) {
s.append(":");
}
}
additionalStorageDirs = s.toString();
}
catch (Exception e) {
NativeApp.reportException(e, null);
Log.e(TAG, "Failed to get SD storage dirs: " + e.toString());
}
Log.i(TAG, "End of storage paths");
File filesDir = this.getFilesDir();
String dataDir = null;
if (filesDir != null) {
// Null has been seen in Google Play stacktraces
dataDir = filesDir.getAbsolutePath();
}
String apkFilePath = appInfo.sourceDir;
String cacheDir = getCacheDir().getAbsolutePath();
String model = Build.MANUFACTURER + ":" + Build.MODEL;
String languageRegion = Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry();
String shortcut = overrideShortcutParam == null ? shortcutParam : overrideShortcutParam;
overrideShortcutParam = null;
NativeApp.audioConfig(optimalFramesPerBuffer, optimalSampleRate);
NativeApp.init(model, deviceType, languageRegion, apkFilePath, dataDir, extStorageDir, externalFilesDir, nativeLibDir, additionalStorageDirs, cacheDir, shortcut, Build.VERSION.SDK_INT, Build.BOARD);
// Allow C++ to tell us to use JavaGL or not.
javaGL = "true".equalsIgnoreCase(NativeApp.queryConfig("androidJavaGL"));
sendInitialGrants();
// OK, config should be initialized, we can query for screen rotation.
updateScreenRotation("Initialize");
// Detect OpenGL support.
// We don't currently use this detection for anything but good to have in the log.
if (!detectOpenGLES20()) {
Log.i(TAG, "OpenGL ES 2.0 NOT detected. Things will likely go badly.");
} else {
if (detectOpenGLES30()) {
Log.i(TAG, "OpenGL ES 3.0 detected.");
} else {
Log.i(TAG, "OpenGL ES 2.0 detected.");
}
}
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
checkForVibrator();
}
mLocationHelper = new LocationHelper(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// android.graphics.SurfaceTexture is not available before version 11.
mCameraHelper = new CameraHelper(this);
}
}
@TargetApi(Build.VERSION_CODES.N)
private void updateSustainedPerformanceMode() {
if (sustainedPerfSupported) {
// Query the native application on the desired rotation.
String str = NativeApp.queryConfig("sustainedPerformanceMode");
try {
int enable = Integer.parseInt(str);
getWindow().setSustainedPerformanceMode(enable != 0);
} catch (NumberFormatException e) {
Log.e(TAG, "Invalid perf mode: " + str);
}
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private void updateScreenRotation(String cause) {
// Query the native application on the desired rotation.
int rot;
String rotString = NativeApp.queryConfig("screenRotation");
try {
rot = Integer.parseInt(rotString);
} catch (NumberFormatException e) {
Log.e(TAG, "Invalid rotation: " + rotString);
return;
}
Log.i(TAG, "Setting requested rotation: " + rot + " ('" + rotString + "') (" + cause + ")");
switch (rot) {
case 0:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
break;
case 1:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case 2:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case 3:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
break;
case 4:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
break;
case 5:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
break;
}
}
private boolean useImmersive() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
return false;
String immersive = NativeApp.queryConfig("immersiveMode");
return immersive.equals("1");
}
@SuppressLint("InlinedApi")
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void updateSystemUiVisibility() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setupSystemUiCallback();
}
// Compute our _desired_ systemUiVisibility
int flags = View.SYSTEM_UI_FLAG_LOW_PROFILE;
if (useImmersive()) {
flags |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
flags |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
flags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
}
View decorView = getWindow().peekDecorView();
if (decorView != null) {
decorView.setSystemUiVisibility(flags);
} else {
Log.e(TAG, "updateSystemUiVisibility: decor view not yet created, ignoring for now");
}
sizeManager.checkDisplayMeasurements();
}
// Need API 11 to check for existence of a vibrator? Zany.
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void checkForVibrator() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (!vibrator.hasVibrator()) {
vibrator = null;
}
}
}
public native boolean runVulkanRenderLoop(Surface surface);
// Tells the render loop thread to exit, so we can restart it.
public native void requestExitVulkanRenderLoop();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sizeManager = new SizeManager(this);
TextRenderer.init(this);
shuttingDown = false;
registerCallbacks();
// This calls NativeApp.setDisplayParameters. Make sure that's done early in order
// to be able to set defaults when loading config for the first time. Like figuring out
// whether to start at 1x or 2x.
sizeManager.updateDisplayMeasurements();
if (!initialized) {
Initialize();
initialized = true;
}
if (mPowerSaveModeReceiver == null) {
mPowerSaveModeReceiver = new PowerSaveModeReceiver(this);
}
// OK, config should be initialized, we can query for screen rotation.
updateScreenRotation("onCreate");
updateSustainedPerformanceMode();
setVolumeControlStream(AudioManager.STREAM_MUSIC);
gainAudioFocus(this.audioManager, this.audioFocusChangeListener);
NativeApp.audioInit();
if (javaGL) {
mGLSurfaceView = new NativeGLView(this);
nativeRenderer = new NativeRenderer(this);
mGLSurfaceView.setEGLContextClientVersion(isVRDevice() ? 3 : 2);
sizeManager.setSurfaceView(mGLSurfaceView);
// Setup the GLSurface and ask android for the correct
// Number of bits for r, g, b, a, depth and stencil components
// The PSP only has 16-bit Z so that should be enough.
// Might want to change this for other apps (24-bit might be useful).
// Actually, we might be able to do without both stencil and depth in
// the back buffer, but that would kill non-buffered rendering.
// It appears some gingerbread devices blow up if you use a config chooser at all ???? (Xperia Play)
//if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// On some (especially older devices), things blow up later (EGL_BAD_MATCH) if we don't set
// the format here, if we specify that we want destination alpha in the config chooser, which we do.
// http://grokbase.com/t/gg/android-developers/11bj40jm4w/fall-back
// Needed to avoid banding on Ouya?
if (Build.MANUFACTURER.equals("OUYA")) {
mGLSurfaceView.getHolder().setFormat(PixelFormat.RGBX_8888);
mGLSurfaceView.setEGLConfigChooser(new NativeEGLConfigChooser());
} else {
// Tried to mess around with config choosers (NativeEGLConfigChooser) here but fail completely on Xperia Play.
// Then I tried to require 8888/16/8 but that backfired too, does not work on Mali 450 which is
// used in popular TVs and boxes like Mi Box. So we'll just get what we get, I guess...
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && !Build.MANUFACTURER.equals("Amazon")) {
// mGLSurfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 8);
// }
}
mGLSurfaceView.setRenderer(nativeRenderer);
setContentView(mGLSurfaceView);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
updateSystemUiVisibility();
}
mSurfaceView = new NativeSurfaceView(NativeActivity.this);
sizeManager.setSurfaceView(mSurfaceView);
Log.i(TAG, "setcontentview before");
setContentView(mSurfaceView);
Log.i(TAG, "setcontentview after");
startRenderLoopThread();
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
updateSustainedPerformanceMode();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
updateSystemUiVisibility();
}
}
private void applyFrameRate(Surface surface, float frameRateHz) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R)
return;
if (mSurface != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
try {
int method = NativeApp.getDisplayFramerateMode();
if (method > 0) {
Log.i(TAG, "Setting desired framerate to " + frameRateHz + " Hz method=" + method);
switch (method) {
case 1:
mSurface.setFrameRate(frameRateHz, Surface.FRAME_RATE_COMPATIBILITY_DEFAULT);
break;
case 2:
mSurface.setFrameRate(frameRateHz, Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE);
break;
case 3:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
mSurface.setFrameRate(frameRateHz, Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE, Surface.CHANGE_FRAME_RATE_ALWAYS);
}
break;
default:
break;
}
}
} catch (Exception e) {
Log.e(TAG, "Failed to set framerate: " + e.toString());
}
}
}
public void notifySurface(Surface surface) {
mSurface = surface;
if (!initialized) {
Log.e(TAG, "Can't deal with surfaces while not initialized");
return;
}
if (!javaGL) {
// If we got a surface, this starts the thread. If not, it doesn't.
if (mSurface == null) {
joinRenderLoopThread();
} else {
startRenderLoopThread();
}
} else if (mSurface != null) {
applyFrameRate(mSurface, 60.0f);
}
updateSustainedPerformanceMode();
}
// The render loop thread (EmuThread) is now spawned from the native side.
protected synchronized void startRenderLoopThread() {
if (javaGL) {
Log.e(TAG, "JavaGL mode - should not get into startRenderLoopThread.");
return;
}
if (mSurface == null) {
Log.w(TAG, "startRenderLoopThread - not starting thread, needs surface");
return;
}
Log.w(TAG, "startRenderLoopThread: Starting thread");
applyFrameRate(mSurface, 60.0f);
runVulkanRenderLoop(mSurface);
}
private synchronized void joinRenderLoopThread() {
if (javaGL) {
Log.e(TAG, "JavaGL - should not get into joinRenderLoopThread.");
return;
}
// This will wait until the thread has exited.
Log.i(TAG, "requestExitVulkanRenderLoop");
requestExitVulkanRenderLoop();
}
@TargetApi(Build.VERSION_CODES.KITKAT)
void setupSystemUiCallback() {
final View decorView = getWindow().peekDecorView();
if (decorView == null || decorView == navigationCallbackView) {
return;
}
sizeManager.setupSystemUiCallback(decorView);
navigationCallbackView = decorView;
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
if (javaGL) {
if (nativeRenderer != null) {
if (nativeRenderer.isRenderingFrame()) {
Log.i(TAG, "Waiting for renderer to finish.");
int tries = 200;
do {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
tries--;
} while (nativeRenderer.isRenderingFrame() && tries > 0);
} else {
Log.i(TAG, "nativerenderer done.");
nativeRenderer = null;
}
}
if (mGLSurfaceView != null) {
mGLSurfaceView.onDestroy();
mGLSurfaceView = null;
}
} else {
if (mSurfaceView != null) {
mSurfaceView.onDestroy();
mSurfaceView = null;
}
mSurface = null;
}
// Probably vain attempt to help the garbage collector...
audioFocusChangeListener = null;
audioManager = null;
sizeManager.setSurfaceView(null);
if (mPowerSaveModeReceiver != null) {
mPowerSaveModeReceiver.destroy(this);
mPowerSaveModeReceiver = null;
}
// TODO: Can we ensure that the GL thread has stopped rendering here?
// I've seen crashes that seem to indicate that sometimes it hasn't...
NativeApp.audioShutdown();
if (shuttingDown) {
NativeApp.shutdown();
unregisterCallbacks();
initialized = false;
}
navigationCallbackView = null;
// Workaround for VR issues when PPSSPP restarts
if (isVRDevice()) {
System.exit(0);
}
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause");
loseAudioFocus(this.audioManager, this.audioFocusChangeListener);
sizeManager.setPaused(true);
NativeApp.pause();
if (!javaGL) {
mSurfaceView.onPause();
Log.i(TAG, "Joining render thread...");
joinRenderLoopThread();
Log.i(TAG, "Joined render thread");
} else {
if (mGLSurfaceView != null) {
mGLSurfaceView.onPause();
} else {
Log.e(TAG, "mGLSurfaceView really shouldn't be null in onPause");
}
}
if (mCameraHelper != null) {
mCameraHelper.pause();
}
Log.i(TAG, "onPause completed");
}
private boolean detectOpenGLES20() {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ConfigurationInfo info = am.getDeviceConfigurationInfo();
return info.reqGlEsVersion >= 0x20000;
}
private boolean detectOpenGLES30() {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ConfigurationInfo info = am.getDeviceConfigurationInfo();
return info.reqGlEsVersion >= 0x30000;
}
@Override
protected void onResume() {
super.onResume();
updateSustainedPerformanceMode();
sizeManager.setPaused(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
updateSystemUiVisibility();
}
// OK, config should be initialized, we can query for screen rotation.
updateScreenRotation("onResume");
Log.i(TAG, "onResume");
if (javaGL) {
if (mGLSurfaceView != null) {
mGLSurfaceView.onResume();
} else {
Log.e(TAG, "mGLSurfaceView really shouldn't be null in onResume");
}
} else {
if (mSurfaceView != null) {
mSurfaceView.onResume();
}
}
if (mCameraHelper != null) {
mCameraHelper.resume();
}
gainAudioFocus(this.audioManager, this.audioFocusChangeListener);
NativeApp.resume();
if (!javaGL) {
// Restart the render loop.
startRenderLoopThread();
}
}
@Override
public void onAttachedToWindow() {
Log.i(TAG, "onAttachedToWindow");
super.onAttachedToWindow();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setupSystemUiCallback();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Log.i(TAG, "onConfigurationChanged");
super.onConfigurationChanged(newConfig);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
updateSystemUiVisibility();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sizeManager.updateDpi((float)newConfig.densityDpi);
}
}
@Override
public void onMultiWindowModeChanged(boolean isInMultiWindowMode, Configuration newConfig) {
// onConfigurationChanged not called on multi-window change
Log.i(TAG, "onMultiWindowModeChanged: isInMultiWindowMode = " + isInMultiWindowMode);
super.onMultiWindowModeChanged(isInMultiWindowMode, newConfig);
sizeManager.checkDisplayMeasurements();
}
// keep this static so we can call this even if we don't
// instantiate NativeAudioPlayer
public static void gainAudioFocus(AudioManager audioManager, AudioFocusChangeListener focusChangeListener) {
if (audioManager != null) {
audioManager.requestAudioFocus(focusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
}
// keep this static so we can call this even if we don't
// instantiate NativeAudioPlayer
public static void loseAudioFocus(AudioManager audioManager, AudioFocusChangeListener focusChangeListener) {
if (audioManager != null) {
audioManager.abandonAudioFocus(focusChangeListener);
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private InputDeviceState getInputDeviceState(InputEvent event) {
InputDevice device = event.getDevice();
if (device == null) {
return null;
}
for (InputDeviceState input : inputPlayers) {
if (input.getDevice() == device) {
return input;
}
}
// None was found, just add and return it.
InputDeviceState state = new InputDeviceState(device);
inputPlayers.add(state);
Log.i(TAG, "Input player registered: desc = " + getInputDesc(device));
return state;
}
protected String getInputDeviceDebugString() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
String buffer = "";
for (InputDeviceState input : inputPlayers) {
buffer += input.getDebugString();
}
if (buffer.length() == 0) {
buffer = "(no devices)";
}
return buffer;
} else {
return "(input device debug not available before Android Kitkat)";
}
}
public boolean IsXperiaPlay() {
return android.os.Build.MODEL.equals("R800a") || android.os.Build.MODEL.equals("R800i") || android.os.Build.MODEL.equals("R800x") || android.os.Build.MODEL.equals("R800at") || android.os.Build.MODEL.equals("SO-01D") || android.os.Build.MODEL.equals("zeus");
}
// We grab the keys before onKeyDown/... even see them. This is also better because it lets us
// distinguish devices.
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1 && !isXperiaPlay) {
InputDeviceState state = getInputDeviceState(event);
if (state == null) {
return super.dispatchKeyEvent(event);
}
// Let's let back and menu through to dispatchKeyEvent.
boolean passThrough = false;
int sources = event.getSource();
// Is this really only for the Xperia Play special handling in OnKeyDown?
// And if so, can we just handle it here instead?
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BACK:
passThrough = true;
break;
default:
break;
}
// Don't passthrough back button if from gamepad.